WPF ComboBox SelectionChanged in MVVM via Behavior

Install-Package Microsoft.Xaml.Behaviors.Wpf

 

//xaml
<Window x:Class="WpfApp46.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"
        WindowState="Maximized"
        xmlns:local="clr-namespace:WpfApp46"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition Height="3*"/>
        </Grid.RowDefinitions>
        <ComboBox Grid.Row="0"
                  FontSize="100"
                  ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                  SelectedItem="{Binding SelectedBook,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                  >
            <behavior:Interaction.Triggers>
                <behavior:EventTrigger EventName="SelectionChanged">
                    <behavior:InvokeCommandAction 
                        Command="{Binding CbxSelectionChangedCommand}"
                        CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ComboBox}},Path=SelectedItem}"/>
                </behavior:EventTrigger>
            </behavior:Interaction.Triggers>
        </ComboBox>

        <ListBox Grid.Row="1"
                 FontSize="30"
                 ItemsSource="{Binding LbxBooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
    </Grid>
</Window>



//cs
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.Eventing.Reader;
using System.Runtime.CompilerServices;
using System.Text;
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;

namespace WpfApp46
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            var vm = new MainVM();
            this.DataContext = vm;
        }
    }

    public class MainVM : INotifyPropertyChanged
    {
        public MainVM()
        {
            InitData();
        }

        private void InitData()
        {
            LbxBooksCollection=new ObservableCollection<Book>();
            BooksCollection =new ObservableCollection<Book>();
            for(int i=0;i<100;i++)
            {
                BooksCollection.Add(new Book()
                {
                    Id=i+1,
                    Name=$"Name_{i+1}",
                    Title=$"Title_{i+1}",
                    ISBN=$"ISBN_{i+1}"
                });
            }
        }

        public event PropertyChangedEventHandler? PropertyChanged;
        private void OnPropertyChanged([CallerMemberName]string propertyName="")
        {
            var handler = PropertyChanged;
            if(handler!=null)
            {
                handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }


        private ObservableCollection<Book> booksCollection;
        public ObservableCollection<Book> BooksCollection
        {
            get
            {
                return booksCollection;
            }
            set
            {
                if(value!= booksCollection)
                {
                    booksCollection = value;
                    OnPropertyChanged();
                }
            }
        }

        private ObservableCollection<Book> lbxBooksCollection;
        public ObservableCollection<Book> LbxBooksCollection
        {
            get
            {
                return lbxBooksCollection;
            }
            set
            {
                if(value!= lbxBooksCollection)
                {
                    lbxBooksCollection = value;
                    OnPropertyChanged();
                }
            }
        }

        private ICommand cbxSelectionChangedCommand;
        public ICommand CbxSelectionChangedCommand
        {
            get
            {
                if(cbxSelectionChangedCommand==null)
                {
                    cbxSelectionChangedCommand= new DelCommand(CbxSelectionChangedCommandExecuted);
                }
                return cbxSelectionChangedCommand;
            }
        }

        private void CbxSelectionChangedCommandExecuted(object? obj)
        {
            var bk = obj as Book;
            if(bk!=null)
            {
                LbxBooksCollection.Add(bk);
            }            
        }
    }

    public class DelCommand : ICommand
    {
        private Action<object?> execute;
        private Predicate<object?> canExecute;
        public DelCommand(Action<object?> executeValue, Predicate<object?> canExecuteValue = null)
        {
            execute = executeValue;
            canExecute = canExecuteValue;
        }

        public event EventHandler? CanExecuteChanged
        {
            add
            {
                CommandManager.RequerySuggested+=value;
            }
            remove
            {
                CommandManager.RequerySuggested -= value;
            }
        }

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

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

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

        public string Title { get; set; }   

        public string ISBN { get; set; }

        public override string ToString()
        {
            return $"{Id},{Name},{Title},{ISBN}";
        }
    }
}

 

 

 

image

 

posted @ 2025-08-19 18:14  FredGrit  阅读(22)  评论(0)    收藏  举报