2010-04-01 75 views
1

我已經有了使用項目模板的列表框。在列表中的每個項目中,按照模板中的定義,有一個按鈕。當用戶單擊按鈕時,我更改數據源中定義列表排序順序的值。更改數據源不是問題,因爲這在我的應用程序模板中工作得很好。在WPF列表框項目模板中捕獲事件

但是,我的下一步是用新的排序數據源重新加載列表框。我試着從tempalte這樣做,但它顯然沒有訪問(或我無法弄清楚如何獲得訪問)到父元素,所以我可以重置.ItemSource屬性與新排序的數據源。

看起來這是可能的,但解決方案是躲避我:(

+0

爲什麼你需要手動重新加載ListBox?如果你的數據源有某種通知機制(例如,如果它是一個'BindingList'),ListBox應該自動注意到它的ItemSource已經改變了。 – Heinzi 2010-04-01 22:02:18

回答

1

您可以使用數據綁定到按鈕的標籤綁定到其ListBox祖先例:

<Grid> 
    <Grid.Resources> 
     <DataTemplate x:Key="myDataTemplate"> 
      <Button Tag="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListBox}}" 
         Click="Button_Click">MyButton</Button> 
     </DataTemplate> 
    </Grid.Resources> 

    <ListBox ItemTemplate="{StaticResource myDataTemplate}" ItemsSource="..." /> 
</Grid> 

而這裏的隱藏代碼:

private void Button_Click(object sender, RoutedEventArgs e) 
    { 
     ListBox myListBox = (ListBox)((Button)sender).Tag; 
     ...do something with myListBox... 
    } 

或者,您可以手動CL在你的代碼中向上看im樹(不需要Tag數據綁定):

private void Button_Click(object sender, RoutedEventArgs e) 
    { 
     DependencyObject search = (DependencyObject)sender; 
     while (!(search is ListBox)) { 
      search = VisualTreeHelper.GetParent(search); 
     } 
     ListBox myListBox = (ListBox)search; 
     ...do something with myListBox... 
    }