WPF树视图中的SelectedItem数据绑定如何检索在WPF-TreeView中选择的项?我想在XAML中这样做,因为我想绑定它。你可能会认为SelectedItem但很明显不存在是只读的,因此是不可用的。这就是我想做的:<TreeView ItemsSource="{Binding Path=Model.Clusters}"
ItemTemplate="{StaticResource ClusterTemplate}"
SelectedItem="{Binding Path=Model.SelectedCluster}" />我想绑定SelectedItem我的模型上的一个属性。但这给了我一个错误:“SelectedItem”属性是只读的,不能从标记中设置。编辑:好吧,这就是我解决这个问题的方法:<TreeView
ItemsSource="{Binding Path=Model.Clusters}"
ItemTemplate="{StaticResource HoofdCLusterTemplate}"
SelectedItemChanged="TreeView_OnSelectedItemChanged" />在我的XAML的代码文件中:private void TreeView_OnSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e){
Model.SelectedCluster = (Cluster)e.NewValue;}
3 回答
慕尼黑8549860
TA贡献1818条经验 获得超11个赞
public class BindableSelectedItemBehavior : Behavior<TreeView>{ #region SelectedItem Property public object SelectedItem { get { return (object)GetValue(SelectedItemProperty); } set { SetValue(SelectedItemProperty, value); } } public static readonly DependencyProperty SelectedItemProperty = DependencyProperty.Register("SelectedItem", typeof(object), typeof(BindableSelectedItemBehavior), new UIPropertyMetadata(null, OnSelectedItemChanged)); private static void OnSelectedItemChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { var item = e.NewValue as TreeViewItem; if (item != null) { item.SetValue(TreeViewItem.IsSelectedProperty, true); } } #endregion protected override void OnAttached() { base.OnAttached(); this.AssociatedObject.SelectedItemChanged += OnTreeViewSelectedItemChanged; } protected override void OnDetaching() { base.OnDetaching(); if (this.AssociatedObject != null) { this.AssociatedObject.SelectedItemChanged -= OnTreeViewSelectedItemChanged; } } private void OnTreeViewSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { this.SelectedItem = e.NewValue; }}
<TreeView> <e:Interaction.Behaviors> <behaviours:BindableSelectedItemBehavior SelectedItem="{Binding SelectedItem, Mode=TwoWay}" /> </e:Interaction.Behaviors></TreeView>
海绵宝宝撒
TA贡献1809条经验 获得超8个赞
public class ExtendedTreeView : TreeView{ public ExtendedTreeView() : base() { this.SelectedItemChanged += new RoutedPropertyChangedEventHandler<object>(___ICH); } void ___ICH(object sender, RoutedPropertyChangedEventArgs<object> e) { if (SelectedItem != null) { SetValue(SelectedItem_Property, SelectedItem); } } public object SelectedItem_ { get { return (object)GetValue(SelectedItem_Property); } set { SetValue(SelectedItem_Property, value); } } public static readonly DependencyProperty SelectedItem_Property = DependencyProperty.Register("SelectedItem_", typeof(object), typeof(ExtendedTreeView), new UIPropertyMetadata(null));}
<local:ExtendedTreeView ItemsSource="{Binding Items}" SelectedItem_="{Binding Item, Mode=TwoWay}"> ..... </local:ExtendedTreeView>
- 3 回答
- 0 关注
- 2595 浏览
添加回答
举报
0/150
提交
取消