wpf - 使用 MVVM 处理 SelectedItem 事件的最简单方法是什么?

标签 wpf mvvm selecteditem

在下面的代码中,当用户选择客户 在组合框中,显示客户姓名在文本框中。我用 ViewModel 上的 ObservableCollection 属性填充 Combox 框,但是如何处理 ViewModel 中的 SelectedItem 事件?

如下所示,使用代码隐藏很容易实现这一点,但是 如何使用 MVVM 模式执行此操作?

我目前有委托(delegate)指挥附加行为在我可以使用的基本 MVVM 模板中,但我不知道如何让它们在“组合框选择新项目”时触发。

查看:

<Window.Resources>
    <DataTemplate x:Key="CustomerTemplate">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding LastName}"/>
        </StackPanel>
    </DataTemplate>
</Window.Resources>

<DockPanel LastChildFill="False" Margin="10">
    <ComboBox 
        x:Name="CustomerList"
        ItemTemplate="{StaticResource CustomerTemplate}"
        HorizontalAlignment="Left"
        DockPanel.Dock="Top" 
        Width="200"
        SelectionChanged="CustomerSelected"
        ItemsSource="{Binding Customers}"/>

    <TextBlock x:Name="CurrentlySelectedCustomer"/>
</DockPanel>

隐藏代码:
private void CustomerSelected(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
    Customer customer = (Customer)CustomerList.SelectedItem;
    CurrentlySelectedCustomer.Text = String.Format("{0} {1}", customer.FirstName, customer.LastName);
}

最佳答案

您应该能够将 ViewModel 中的属性绑定(bind)到组合框的 SelectedItem 属性。如果您将其设置为双向绑定(bind),您将在 SelectedItem 更改时收到通知,因为它将触发属性上的 set 方法。

View 模型:

public ObservableCollection Customers
{
   get { return _customers; }
   set
   {
       if (_customers != value)
       {
           _customers = value;
           OnPropertyChanged("Customers");
       }
   }
}

public Customer SelectedCustomer
{
   get { return _selectedCustomer; }
   set
   {
       if (_selectedCustomer != value)
       {
           _selectedCustomer= value;
           LastName= value.LastName;
           OnPropertyChanged("SelectedCustomer");
       }
   }
}

public Customer LastName
{
   get { return _lastName; }
   set
   {
       if (_lastName!= value)
       {
           _lastName= value;
           OnPropertyChanged("LastName");
       }
   }
}

xml:
<DockPanel LastChildFill="False" Margin="10">
    <ComboBox 
        x:Name="CustomerList"
        ItemTemplate="{StaticResource CustomerTemplate}"
        HorizontalAlignment="Left"
        DockPanel.Dock="Top" 
        Width="200"
        SelectedItem="{Binding SelectedCustomer, Mode=TwoWay}"
        ItemsSource="{Binding Customers}"/>

    <TextBlock x:Name="CurrentlySelectedCustomer"
               Text="{Binding LastName}"/>
</DockPanel>

关于wpf - 使用 MVVM 处理 SelectedItem 事件的最简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1011750/

相关文章:

c# - 选项卡控件默认选择第一个选项卡

c# - 在 xaml 中将 DockLayoutManager 与 View 模型文件绑定(bind)

vb.net - 从后端刷新时不要触发 ComboBox SelectionChanged

.net - 在 ComboBox 中以不同方式显示所选项目

c# - WPF MVVM : Postpone rendering of View until DataContext is set

c# - 为什么 MenuItem 标题前面有下划线?

.net - 使 WPF ListBoxItems 可选

c# - 使用运行时生成的控件保存控件窗口并重新加载为以前的状态

c# - 按搜索字符串过滤 CollectionViewSource - 绑定(bind)到 itemscontrol (WPF MVVM)