我有一个TreeView
,其中填充了我的自定义类型ToolbarTreeItem
的项目。现在,当用户单击某个项目时,我想知道在MainViewModel
中单击了哪个项目。
我想在没有任何代码的情况下实现这一点,但是要使用RelayCommand
。
那么,如何在不使用标准事件的情况下将所选项目传递到RelayCommand
呢?
MainViewModel.cs中的代码段:
private ToolbarTreeItem _selectedItem;
private RelayCommand<ToolbarTreeItem> _changeSelectedItem;
public RelayCommand<ToolbarTreeItem> ChangeSelectedItem
{
get
{
return _changeSelectedItem ?? (_changeSelectedItem = new RelayCommand<ToolbarTreeItem>(selectedItem =>
{
_selectedItem = selectedItem;
}));
}
}
Toolbar.xaml中的Xaml代码段:
<TreeView SelectedItemChanged="???" />
答案 0 :(得分:0)
行为:
public class TreeViewSelection : Behavior<TreeView>
{
public static readonly DependencyProperty CurrentSelectionProperty = DependencyProperty.Register("CurrentSelection", typeof(object), typeof(TreeViewSelection), new PropertyMetadata(default(object)));
public object CurrentSelection
{
get
{
return (object)GetValue(CurrentSelectionProperty);
}
set
{
SetValue(CurrentSelectionProperty, value);
}
}
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.SelectedItemChanged += TreeView_SelectedItemChanged;
}
private void TreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
CurrentSelection = e.NewValue;
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.SelectedItemChanged -= TreeView_SelectedItemChanged;
}
}
XAML:
xmlns:i =“ clr-namespace:System.Windows.Interactivity; assembly = System.Windows.Interactivity” xmlns:b =“ clr-namespace:NameSpaceWhereBahaviorDefined”
<TreeView ...>
<i:Interaction.Behaviors>
<b:TreeViewSelection CurrentSelection = "{Binding VMSelection}" />
</i:Interaction.Behaviors>
</TreeView>