项目选择上的WPF调用函数(使用MVVM范例)

本文关键字:使用 MVVM 范例 函数 调用 选择 WPF 项目 | 更新日期: 2023-09-27 17:58:28

我有一个ListBox,它绑定到客户的ObservableCollection。这方面的XAML代码是:

<ListBox x:Name="lb_Customers" Height="683" ItemsSource="{Binding Path=Customers, UpdateSourceTrigger=PropertyChanged}">
     <ListBox.ItemTemplate>
          <DataTemplate>
               <Label Margin="0,0,0,0" Padding="0,0,0,0" Content="{Binding Name}" />
          </DataTemplate>
      </ListBox.ItemTemplate>
</ListBox>

这指向我的MainViewModel类中的一些代码:

public ObservableCollection<Customer> Customers
{
    get { return _customers; }
    set
    {
        Set("Customers", ref _customers, value);
        this.RaisePropertyChanged("Customers");
    }
}

当我在这个列表框中选择一个客户时,我想执行一些代码来编译客户的订单历史记录。

然而,我不知道如何使用DataBinding/CommandBinding来实现这一点。

我的问题是:我从哪里开始

项目选择上的WPF调用函数(使用MVVM范例)

正如Tormond所建议的:

更改

<ListBox x:Name="lb_Customers" Height="683" ItemsSource="{Binding Path=Customers, UpdateSourceTrigger=PropertyChanged}">

<ListBox x:Name="lb_Customers" Height="683" ItemsSource="{Binding Path=Customers, UpdateSourceTrigger=PropertyChanged}", SelectedValue="{Binding SelectedCustomer}">

然后在ViewModel中添加:

private Customer _selectedCustomer;
public Customer SelectedCustomer
{
    get {}
    set
    {
        if (_selectedCustomer != value)
        {
            Set("SelectedCustomer", ref _selectedCustomer, value);
            this.RaisePropertyChanged("SelectedCustomer");
            // Execute other changes to the VM based on this selection...
        }
    }
}

您可以将"currentlyselected"对象添加到视图模型中,并将其绑定到列表框的"SelectedItem"属性。然后在"set"访问器中执行所需操作。