2012-03-13 72 views
0

我有一個綁定到一個ObservableCollection一個ListBox:更改標籤內容基於列表框選擇

<ListBox Name="ListBoxItemsList"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <Grid Margin="0" FlowDirection="RightToLeft"> 
       <Button Content="Add me!" Click="AddItem" /> 
       <TextBlock Text="{Binding Path=name}" /> 
       <TextBlock Text="{Binding Path=description}" /> 
      </Grid> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

的的ObservableCollection對象有幾個屬性,包括uniqueIDnamedescriptioncolourflavour。根據列表框中的選定項目,我想用選定項目的屬性填充一些標籤。此外,每個項目的按鈕應該執行一個獨特的操作(即添加一個相關項目到一個數組),但我不知道如何發送一個唯一的參數到AddItem()方法。我認爲這將是一個常見用例,但我無法通過Google搜索找到任何東西。

謝謝。

+1

'我想要一些標籤的細節來顯示所選項目的屬性'...'一些標籤的細節顯示'?? – 2012-03-13 14:32:36

+0

謝謝,我重寫了這句話。 – dotancohen 2012-03-13 18:14:28

+0

你是usijng mvvm嗎? – 2012-03-13 18:27:46

回答

1

根據ListBox中選定的項目,我想一些細節標籤 顯示所選項目的屬性

您可以在ListBox.SelectedItem綁定到一個DependencyProperty,然後就結合這財產這些標籤。

此外,每個項目的按鈕應該執行一個獨特的動作(即 添加相關的項目添加到陣列中的一個),但我想不出 如何獨特的參數發送到的AddItem()方法。

您可以在產品ID添加到Button.Tag

<Button Content="Add me!" Click="AddItem" Tag={Binding Path=id} /> 

然後,只需獲得按鈕標籤發件人

public void button_clicked(object sender, event e) { 
    int id = ((Button)sender).Tag as Int32; 
    ... 
} 

編輯:您還可以綁定完整Item而不僅僅是按鈕標籤的Id。

+0

或者,您可以從項目中公開一個ICommand屬性,並將Button Command屬性綁定到該項目(google DelegateCommand以獲取更多詳細信息)。 – Scroog1 2012-03-13 14:57:15

+0

謝謝丹尼爾!完善! – dotancohen 2012-03-14 17:34:51