WPF behavior InvokeCommandAction CommandParameter

<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);
        }
    }
}

 

posted @ 2024-09-20 11:38  FredGrit  阅读(7)  评论(0编辑  收藏  举报