首页 > 其他分享 >WPF behavior InvokeCommandAction CommandParameter

WPF behavior InvokeCommandAction CommandParameter

时间:2024-09-20 11:35:48浏览次数:1  
标签:CommandParameter Windows object System private InvokeCommandAction using WPF pub

<ListBox x:Name="lbx"
         SelectedIndex="0"
         ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
         VirtualizingPanel.IsContainerVirtualizable="True"
         VirtualizingPanel.IsVirtualizing="True"
         VirtualizingPanel.ScrollUnit="Item"
         VirtualizingPanel.VirtualizationMode="Recycling">
    <behavior:Interaction.Triggers>
        <behavior:EventTrigger EventName="SelectionChanged">
            <behavior:InvokeCommandAction Command="{Binding SelectionChangedCmd}"
                                          CommandParameter="{Binding Path=SelectedItem,ElementName=lbx}"/>
        </behavior:EventTrigger>
    </behavior:Interaction.Triggers>
</ListBox>

 private void InitCmds()
 {
     SelectionChangedCmd = new DelCmd(SelectionChangedCmdExecuted);
 }

 private void SelectionChangedCmdExecuted(object obj)
 {
     var bk = obj as Book;
     if (bk != null)
     {
         ImgTitle = bk.Name;
         MessageBox.Show(ImgTitle, "Image Title", MessageBoxButton.OK);
     }
 }

 

 

 

 

 

 

 

//Full code

 

//converter
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace WpfApp383
{
    public class SizeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return System.Convert.ToDouble(value?.ToString()) * System.Convert.ToDouble(parameter?.ToString());
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}


//xaml
<Window x:Class="WpfApp383.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:behavior="http://schemas.microsoft.com/xaml/behaviors"
        xmlns:local="clr-namespace:WpfApp383"
        mc:Ignorable="d" WindowState="Maximized"        
        Title="{Binding ImgTitle,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
        Height="450" Width="800">
    <Window.DataContext>
        <local:BookVM/>
    </Window.DataContext>
    <Window.Resources>
        <local:SizeConverter x:Key="sizeConverter"/>
    </Window.Resources>
    <ListBox x:Name="lbx"
             SelectedIndex="0"
             ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
             VirtualizingPanel.IsContainerVirtualizable="True"
             VirtualizingPanel.IsVirtualizing="True"
             VirtualizingPanel.ScrollUnit="Item"
             VirtualizingPanel.VirtualizationMode="Recycling">
        <behavior:Interaction.Triggers>
            <behavior:EventTrigger EventName="SelectionChanged">
                <behavior:InvokeCommandAction Command="{Binding SelectionChangedCmd}"
                                              CommandParameter="{Binding Path=SelectedItem,ElementName=lbx}"/>
            </behavior:EventTrigger>
        </behavior:Interaction.Triggers>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto"/>
                        <ColumnDefinition/>
                    </Grid.ColumnDefinitions>
                    <Image Source="{Binding ImgUrl}"
          Width="{Binding Path=ActualWidth,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Window},
       Converter={StaticResource sizeConverter},ConverterParameter=0.3}"/>
                    <TextBlock FontSize="200" Foreground="Red" 
                               Grid.Column="1"
                               Text="{Binding Name}"
                               HorizontalAlignment="Center"
                               VerticalAlignment="Center"/>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Window>


//xaml.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;

namespace WpfApp383
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            //FrameworkElementFactory panelFactory=new FrameworkElementFactory(typeof(WrapPanel));
            //lbx.ItemsPanel=new ItemsPanelTemplate(panelFactory);
        }
    }

    public class BookVM : INotifyPropertyChanged
    {
        public BookVM()
        {
            InitData();
            InitCmds();
        }

        private void InitCmds()
        {
            SelectionChangedCmd = new DelCmd(SelectionChangedCmdExecuted);
        }

        private void SelectionChangedCmdExecuted(object obj)
        {
            var bk = obj as Book;
            if (bk != null)
            {
                ImgTitle = bk.Name;
                MessageBox.Show(ImgTitle, "Image Title", MessageBoxButton.OK);
            }
        }

        private void InitData()
        {
            var imgsList = Directory.GetFiles("../../Images");
            if (imgsList != null && imgsList.Any())
            {
                BooksCollection = new ObservableCollection<Book>();
                int imgsCount = imgsList.Count();
                for (int i = 0; i < 1000000; i++)
                {
                    BooksCollection.Add(new Book()
                    {
                        Id = i,
                        Name = $"Name_{i}",
                        ImgUrl = imgsList[i % imgsCount],
                    });
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanegd(string propName)
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler?.Invoke(this, new PropertyChangedEventArgs(propName));
            }
        }

        private ObservableCollection<Book> books;
        public ObservableCollection<Book> BooksCollection
        {
            get
            {
                return books;
            }
            set
            {
                if (value != books)
                {
                    books = value;
                    OnPropertyChanegd(nameof(BooksCollection));
                }
            }
        }

        private string imgTitle;
        public string ImgTitle
        {
            get
            {
                return imgTitle;
            }
            set
            {
                if (value != imgTitle)
                {
                    imgTitle = value;
                    OnPropertyChanegd(nameof(ImgTitle));
                }
            }
        }

        public DelCmd SelectionChangedCmd { get; set; }
    }

    public class Book
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public string ImgUrl { get; set; }
    }

    public class DelCmd : ICommand
    {
        public event EventHandler CanExecuteChanged
        {
            add
            {
                CommandManager.RequerySuggested += value;
            }
            remove
            {
                CommandManager.RequerySuggested -= value;
            }
        }

        private Action<object> execute;
        private Predicate<object> canExecute;

        public DelCmd(Action<object> executeValue, Predicate<object> canExecuteValue)
        {
            execute = executeValue;
            canExecute = canExecuteValue;
        }

        public DelCmd(Action<object> executeValue):this(executeValue, null)
        {

        }

        public bool CanExecute(object parameter)
        {
            if(canExecute==null)
            {
                return true;
            }
            return canExecute(parameter);
        }

        public void Execute(object parameter)
        {
            execute(parameter);
        }
    }
}

 

标签:CommandParameter,Windows,object,System,private,InvokeCommandAction,using,WPF,pub
From: https://www.cnblogs.com/Fred1987/p/18422168

相关文章

  • WPF behavior InvokeCommndAction PassEventArgsToCommand
    //xaml<ListBoxx:Name="lbx"SelectedIndex="0"ItemsSource="{BindingBooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"VirtualizingPanel.IsContainerVirtualizable="Tru......
  • WPF System.Windows.Media.Color A value must be set, display ball and number in c
    privateColorGetRndColor(){Colorcr=newColor();cr.A=255;cr.R=(byte)(rnd.Next(0,255));cr.G=(byte)(rnd.Next(0,255));cr.B=(byte)(rnd.Next(0,255));returncr;}         //usercontrol.......
  • WPF Customcontrol with ellipse and textblock display randomly in canvas of mainw
    //usercontrol.xaml<UserControlx:Class="WpfApp381.ElpImgTbk"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"......
  • WPF Element Width Height is percent of Parent element via converter ,converterpa
    //converterusingSystem;usingSystem.Collections.Generic;usingSystem.Globalization;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Data;namespaceWpfApp380{publicclassSizeConverter:IValueConverter......
  • WPF 异步
    在WPF中,异步编程非常重要,尤其是为了保持UI线程的响应性。由于WPF的UI操作必须在主线程上进行,耗时的任务(如文件读写、网络请求等)如果直接在UI线程上执行,会导致UI冻结,界面无法响应用户操作。因此,使用异步编程可以避免这些问题,使得任务能够在后台线程中执行,同时保持U......
  • C# + WPF 音频播放器 界面优雅,体验良好mL
    合集-.NET开源工具(17)1..NET开源快捷的数据库文档查询和生成工具07-312..NET结果与错误处理利器FluentResults08-013..NET+WPF桌面快速启动工具GeekDesk08-194.Gradio.NET支持.NET8简化Web应用开发08-265..NET开源实时监控系统-WatchDog08-276.实用接地气的.NE......
  • WPF 数据绑定之ValidationRule数据校验综合Demo
    一、概述我们利用ValidationRule以及ErrorTemplate来制作一个简单的表单验证。二、Demo核心思想:我们在ValidationRule中的Validate函数中进行验证,然后将验证结果存放至一个预先定义好的全局资源中,这样其他控件就可以根据验证结果来进行相应的处理,代码参见以下:usingSystem......
  • WPF ListBox ContextMenu MenuItem Command CommandParameter Path PlacementTarget
    <ListBox.ContextMenu><ContextMenu><MenuItemHeader="ExportNewtonSoftJson"FontSize="50"Foreground="Red"Command="{BindingExportNewt......
  • WPF ListBox ListBox use UserControl
    //usercontrolxaml<UserControlx:Class="WpfApp379.ImgTbk"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xml......
  • WPF Expander ExpandDirection Left,Right,Up,Down
    //xaml<Windowx:Class="WpfApp378.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.mi......