2013-02-07 95 views
0

我有一个ListBox绑定到ObservableCollection客户。这样做的XAML代码:项目选择WPF调用函数(使用MVVM范例)

<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来做到这一点。

我的问题:我甚至在哪里开始?

回答

1

由于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}"> 

然后在您的视图模型添加:

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... 
     } 
    } 
} 
+0

如何'SelectedValue'从'SelectedItem'不同?试图绑定SelectedItem没有奏效,但我会尝试这个。我很好奇为什么一个人在另一个人上工作。 – Emily

+0

http://stackoverflow.com/questions/4902039/difference-between-selecteditem-selectedvalue-and-selectedvaluepath这个SO线程很好地描述了SelectedValue和SelectedItem之间的区别 – EtherDragon

1

您可以将“当前选定”对象添加到您的视图模型并将其与列表框的“SelectedItem”属性绑定。然后在“设置”访问器中执行所需的操作。

相关问题