无法将TreeViewItem的IsSelected属性绑定到ViewModel

时间:2014-03-20 12:06:27

标签: c# wpf mvvm

在这里找到了很多答案,但没有一个对我有用。这是我的XAML

<UserControl x:Class="Helper.View.TreeViewUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             xmlns:this="clr-namespace:Helper.Model"
             xmlns:vm="clr-namespace:Helper.ViewModel"
              DataContext="{DynamicResource TreeNodeViewModel}">
    <UserControl.Resources>
        <vm:TreeNodeViewModel x:Key="TreeNodeViewModel"/>
    </UserControl.Resources>
    <Grid>
        <TreeView ItemsSource="{Binding CodeBookEnties}" >
            <TreeView.ItemContainerStyle>
                <Style TargetType="{x:Type TreeViewItem}">
                    <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
                    <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
                    <Setter Property="FontWeight" Value="Normal" />
                    <Style.Triggers>
                        <Trigger Property="IsSelected" Value="True">
                            <Setter Property="FontWeight" Value="Bold" />
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </TreeView.ItemContainerStyle>

            <TreeView.Resources>
                <HierarchicalDataTemplate ItemsSource="{Binding DocSetCollection}" DataType="{x:Type this:CodeBookEntity}">
                    <Label Content="{Binding CodeBookName}"/>
                </HierarchicalDataTemplate>

                <HierarchicalDataTemplate ItemsSource="{Binding FieldCollection}" DataType="{x:Type this:DocumentEntity}">
                    <Label Content="{Binding DocSetName}"/>
                </HierarchicalDataTemplate>

                <DataTemplate DataType="{x:Type this:FieldEntity}">
                    <Label Content="{Binding FieldName}"/>
                </DataTemplate>
            </TreeView.Resources>
        </TreeView>
    </Grid>
</UserControl>

我的viewmodel类是这样的:

namespace Helper.ViewModel
{
    public class TreeNodeViewModel : ViewModelBase
    {
        private ObservableCollection<DocumentEntity> children;
        private CodeBookEntity _codeBookEntity;
        private ObservableCollection<CodeBookEntity> codeBookEntities;
        //TreeNodeViewModel _parent = null;
        bool _isExpanded = false;
        bool _isSelected = false;


        public TreeNodeViewModel()
        {
            Mediator.Instance.Register(
                   //Callback delegate, when message is seen
                   (Object o) =>
                   {
                       ParentNode = (CodeBookEntity)o;
                   }, ViewModelMessages.CodeBookCreated);          
        }

        public override string ToString() {
            return _codeBookEntity.CodeBookName;
        }

        public ObservableCollection<DocumentEntity> Children
        {
            get { return CodeBookEnties[0].DocSetCollection; }

            set {

                CodeBookEnties[0].DocSetCollection = value;

                //OnPropertyChanged("CodeBookEnties");
            }
        }

        public CodeBookEntity ParentNode 
        {
            get { return _codeBookEntity; }

            set { 
                _codeBookEntity = value;
                if (CodeBookEnties == null)
                {
                    CodeBookEnties = new ObservableCollection<CodeBookEntity>();
                }


                CodeBookEnties.Add(_codeBookEntity);   

                OnPropertyChanged("ParentNode");
            }
        }
        public string Name {
            get { return _codeBookEntity.CodeBookName; }
        }

        public string Description 
        { get { return _codeBookEntity.CodeBookDescription; } }

        #region Presentation Members

        #region IsExpanded

        /// <summary>
        /// Gets/sets whether the TreeViewItem 
        /// </summary>
        public bool IsExpanded
        {
            get { return _isExpanded; }
            set
            {
                if (value != _isExpanded)
                {
                    _isExpanded = value;
                    this.OnPropertyChanged("IsExpanded");
                }

                // Expand all the way up to the root.
                //if (_isExpanded && _parent != null)
                //    _parent.IsExpanded = true;
            }
        }

        #endregion // IsExpanded

        #region IsSelected

        /// <summary>
        /// Gets/sets whether the TreeViewItem 
        /// associated with this object is selected.
        /// </summary>
        public bool IsSelected
        {
            get { return _isSelected; }
            set
            {
                if (value != _isSelected)
                {
                    _isSelected = value;
                    this.OnPropertyChanged("IsSelected");
                }
            }
        }

        #endregion // IsSelected

        #region NameContainsText

        public bool NameContainsText(string text)
        {
            if (String.IsNullOrEmpty(text) || String.IsNullOrEmpty(this.Name))
                return false;

            return this.Name.IndexOf(text, StringComparison.InvariantCultureIgnoreCase) > -1;
        }

        #endregion // NameContainsText

        #endregion // Presentation Members    

        public bool IsLeaf {
            get { return !Children.Any(); }
        }

        public ObservableCollection<CodeBookEntity> CodeBookEnties
        {
            get
            {
                return codeBookEntities;
            }
            set
            {
                if (codeBookEntities == null)
                {
                    codeBookEntities = new ObservableCollection<CodeBookEntity>();
                }
                codeBookEntities = value;
                OnPropertyChanged("CodeBookEnties");
            }
        }
    }
}

我在usercontrol中使用了此mainwindow。 每当有任何代码簿添加时,我将通过中介类将该信息发送到此treeviewmodel。 基于此,它将更新其数据。能够毫无问题地添加最多3个级别的节点。

当我在调试时,选择treeview中的任何项目时,treeviewitem会变为粗体,但IsSelected属性未受到影响。每当我选择一个元素时,我必须根据它的选择(CodeBook,Document,Field是这里的类的层次结构)得到它的类,以便我可以在以后处理该元素。
不确定是什么错误。请帮我。

由于 拉尼

1 个答案:

答案 0 :(得分:1)

您的代码存在许多问题。像这样使用Binding会导致错误,因为您在IsSelected中设置为DataContext的对象中寻找TreeViewItem属性在视图模型中:

<Style TargetType="{x:Type TreeViewItem}">
    <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
    <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
    <Setter Property="FontWeight" Value="Normal" />
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="FontWeight" Value="Bold" />
        </Trigger>
    </Style.Triggers>
</Style>

如果确实希望数据绑定到您的视图模型的TreeViewItem.IsSelected属性,那么您可以尝试使用RelativeSource Binding代替:

<Setter Property="IsSelected" Value="{Binding DataContext.IsSelected, RelativeSource={
    RelativeSource AncestorType={x:Type YourPrefix:YourView}}, Mode=TwoWay}" />

请注意,这将在对象中搜索名为IsSelected的属性,该对象是绑定到视图/ UserControl DataContext属性的数据...我假设这将是您的视图模型。我无法确认这是否会实际工作...输入您的下一个问题。

TreeViewItem.IsSelected属性通常是绑定到绑定到TreeViewItem 的数据的数据对象的属性的数据。除了任何其他原因之外,通常这样做是因为TreeView可以选择多个TreeViewItem,并且视图模型中的一个属性无法全部引用它们。有关数据绑定的更多信息,请参阅Stack Overflow上的Get Selected TreeViewItem Using MVVMWPF MVVM TreeView SelectedItem个问题。