我正在使用自定义模板绑定TreeView。我在模板中有一个按钮,当用户点击它时,我需要找出用于绑定特定模板实例的数据项。
因此,如果我将TreeView绑定到IList,我需要获取为特定模板实例提供数据的MyTreeItem。
我的代码如下所示:
<TreeView Grid.Column="1" HorizontalAlignment="Left" Height="268" Margin="10,41,0,0" VerticalAlignment="Top" Width="197" x:Name="TrViewCodeTree">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}" DataType="roslynDemos:TrViewCodeTreeItem">
<WrapPanel>
<Label Content="Node Type:" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Height="26" Width="70"/>
<TextBlock Text="{Binding NodeType}" Margin="10,10,0,0"></TextBlock>
<Label Content="Node Position" Margin="10,10,0,0" VerticalAlignment="Top" Height="26" Width="80"/>
<TextBlock Text="{Binding Position}" Margin="10,10,0,0"></TextBlock>
<Label Content="Node Length" Margin="10,10,0,0" VerticalAlignment="Top" Height="26" Width="75"/>
<TextBlock Text="{Binding Length}" Margin="10,10,0,0"></TextBlock>
<Button x:Name="BtnSelect" Click="BtnSelect_OnClick"></Button>
</WrapPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
答案 0 :(得分:1)
private void BtnSelect_OnClick(object sender, RoutedEventArgs e)
{
var button = sender as Button;
var dataitem = button.DataContext as [Your DataItem Class Here];
dataitem.[DoStuffHere]();
}