我要求在窗口左侧将菜单实现为树视图。
我知道如何使用(菜单)数据(mvvm方式)填充树视图。
但是:我如何将树视图中的每个对象连接到ICommand(在Viewmodel中)?所以,例如双击一个对象会导致打开一个窗口??
提前致谢
答案 0 :(得分:0)
我认为这个问题应该以另一种方式解决,但......
这是一个示例TreeViewItem
public class EditableTreeViewItem : TreeViewItem {
public ICommand DoubleClickCommand {
get { return (ICommand)GetValue(DoubleClickCommandProperty); }
set { SetValue(DoubleClickCommandProperty, value); }
}
// Using a DependencyProperty as the backing store for DoubleClickCommand. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DoubleClickCommandProperty =
DependencyProperty.Register("DoubleClickCommand", typeof(ICommand), typeof(EditableTreeView), new UIPropertyMetadata(null));
protected override void OnPreviewMouseDoubleClick(MouseButtonEventArgs e) {
if (this.DoubleClickCommand!= null) {
this.DoubleClickCommand.Execute(this.DataContext);
e.Handled = true;
}
base.OnPreviewMouseDoubleClick(e);
}
protected override DependencyObject GetContainerForItemOverride() {
return new EditableTreeViewItem();
}
protected override bool IsItemItsOwnContainerOverride(object item) {
return item is EditableTreeViewItem;
}
}
以及使用此项目的树视图
public class EditableTreeView : TreeView {
//generate the tree view item
protected override DependencyObject GetContainerForItemOverride() {
EditableTreeViewItem item = new EditableTreeViewItem();
return item;
}
protected override bool IsItemItsOwnContainerOverride(object item) {
return item is EditableTreeViewItem;
}
}
现在正如一些聪明人所说的那样,你最好使用菜单和造型。现在,当您双击treeview项时,它将调用命令而不是按原样扩展/折叠。
这就是你在xaml中使用它的方式
<controls:EditableTreeViewMode=OneWayToSource}"
ItemsSource="{Binding Path=MyItemsSource}">
<controls:EditableTreeView.ItemContainerStyle>
<!-- This Style binds a TreeViewItem to a the ViewModel. -->
<Style
TargetType="{x:Type controls:EditableTreeViewItem}">
<Setter
Property="DoubleClickCommand"
Value="{Binding OpenNewWindowCommand}" />
</Style>
</controls:EditableTreeView.ItemContainerStyle>
</controls:EditableTreeView>