WPF MVVM数据网格视图所选单元格已更改

本文关键字:单元格 选单 视图 MVVM 数据 数据网 网格 WPF | 更新日期: 2023-09-27 18:29:51

我是WPF MVVM的新手。我想知道如何在我的ViewModel中检测SelectedCellsChanged事件。是否有任何方法可以在不将任何代码放入代码隐藏文件的情况下检测该事件。这是我的密码。

主窗口.xaml

    <Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"              
    Title="MainWindow" Height="350" Width="525"
    DataContext="{StaticResource CusVM}">
<Grid>
    <Button x:Name="myButton" Command="{Binding MyButtonClickCommand}" Width="100" Height="50" Content="click" Margin="0,10,417,260" />
    <Label Content="{Binding Name}" Margin="105,37,23,251" />
    <TextBox x:Name="inputBox1" Width="200" Height="30" Margin="22,74,295,216" Text="{Binding Text1, UpdateSourceTrigger=PropertyChanged}"  />
    <TextBox Width="200" Height="30" Margin="263,74,54,216"   />
    <ComboBox HorizontalAlignment="Left" Margin="122,10,0,0" VerticalAlignment="Top" Width="236" ItemsSource="{Binding Addresses}" SelectedItem="{Binding SelectedAddress}" DisplayMemberPath="AddressLine1"  >
    </ComboBox>
    <DataGrid Margin="0,109,0,10" ItemsSource="{Binding Addresses}"/>
</Grid>

视图模型:CustomerViewModel

    namespace WpfApplication1.ViewModels
{
    public class CustomerViewModel : EventBase
    {
    public ICommand MyButtonClickCommand
    {
        get { return new DelegateCommand(FuncToCall, FuncToEvaluate); }
    }
    private Address selected_address;
    public Address SelectedAddress
    {
        get { return selected_address; }
        set { selected_address = value; OnPropertyChanged("SelectedAddress"); Name = value.AddressLine1; }
    }
    IEnumerable<Address> addresses = new List<Address>();
    public IEnumerable<Address> Addresses
    {
        get { return addresses; }
        set 
        { 
            addresses = value;
            OnPropertyChanged("Addresses");
        }
    }
    public CustomerViewModel()
    {
        fillList();
    }
    private void fillList()
    {
        List<Address> addr = new List<Address>();
        addr.Add(new Address() { AddressID=1, AddressLine1="test1"});
        addr.Add(new Address() { AddressID=2, AddressLine1="test2"});
        addr.Add(new Address() { AddressID = 3, AddressLine1 = "test3" });
        addresses = addr;
    }

    private string text1;
    public string Text1
    {
        get { return text1; }
        set { 
            text1 = value;
            OnPropertyChanged("Text1");
            Name = text1;
        }
    }

    private string name;
    public string Name
    {
        get { return name; }
        set { 
            name = value;
            OnPropertyChanged("Name");
        }
    }
    private void FuncToCall(object context)
    {
        Name = "test result";
    }
    private bool FuncToEvaluate(object context)
    {
        return true;
    }

}
}

WPF MVVM数据网格视图所选单元格已更改

我想你可能会在这里找到答案。我本想把它作为一个评论来添加,但我还没有足够的代表。