2013-02-07 97 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」屬性綁定。然後在「設置」訪問器中執行所需的操作。

相關問題