当我单击树上的按钮时,我只想在树视图中标识选定的节点,请考虑下图:
Treeview绑定到viewmodel,当单击加号按钮时,我有一个属性可保存该值,应设置所选节点的值。在单击加号按钮之前,首先单击“样本节点”时才设置所选值。下面是我的xaml的代码:
<TreeView x:Name="tree" ItemsSource="{Binding SectorTree, Mode=OneWay}" MinHeight="150">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children, Mode=OneTime}">
<StackPanel Orientation="Horizontal">
<Button HorizontalAlignment="Center" Command="{Binding SelectedItemChangedCommand, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
ToolTip="Edit sector name" Background="Transparent" BorderThickness="0">
<Button.Content>
<Image Width="14" Height="14" Margin="0,0,0,0" Source="path_of_image" />
</Button.Content>
</Button>
<ContentPresenter Content="{Binding SectorName, Mode=OneTime}" Margin="2,0" />
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</Style>
</TreeView.ItemContainerStyle>
</TreeView>
答案 0 :(得分:0)
这是我解决TreeView中按钮的Click事件中的相同问题的方法。
向绑定到每个TreeView节点的MyNodeClass添加“ Me”属性:
public object Me { get { return this; } }
将Button的Tag属性绑定给我:
Button Tag="{Binding Me}" Click="Button_Click"
在Button_Click(对象发送方...)事件中查找实例:
MyNodeClass x = ((Button)sender).Tag as MyNodeClass
答案 1 :(得分:0)
目前尚不清楚您要通过将此按钮添加到TreeView数据模板来解决什么问题。
TreeView已经具有一个SelectedItemChanged
事件和一个SelectedItem
属性。
替代方法是使用Behavior
向Treeiew添加新的可绑定BoundSelectedItem属性。这将返回数据项类,而不是TreeViewItem实例。
public class perTreeViewHelper : Behavior<TreeView>
{
public object BoundSelectedItem
{
get => GetValue(BoundSelectedItemProperty);
set => SetValue(BoundSelectedItemProperty, value);
}
public static readonly DependencyProperty BoundSelectedItemProperty =
DependencyProperty.Register("BoundSelectedItem",
typeof(object),
typeof(perTreeViewHelper),
new FrameworkPropertyMetadata(null,
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
OnBoundSelectedItemChanged));
private static void OnBoundSelectedItemChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
if (args.NewValue is perTreeViewItemViewModelBase item)
item.IsSelected = true;
}
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.SelectedItemChanged += OnTreeViewSelectedItemChanged;
}
protected override void OnDetaching()
{
AssociatedObject.SelectedItemChanged -= OnTreeViewSelectedItemChanged;
base.OnDetaching();
}
private void OnTreeViewSelectedItemChanged(object obj, RoutedPropertyChangedEventArgs<object> args)
{
BoundSelectedItem = args.NewValue;
}
}
有关我最近的blog post的更多详细信息。