WPF MVVM TreeView选择的项目不填充当前选择对象

时间:2010-07-02 21:50:07

标签: wpf mvvm treeview

我正在使用WCF和MVVM模式来填充树视图控件,我需要将所选项作为参数传递给视图模型中的另一个方法(以填充不同的控件)。

树视图填充得很好但是所选的值没有传递给视图模型。例如在viewmodel中:

    private ICollectionView m_SuppliersView;
    public ObservableCollection<SupplierItem> SupplierItems
    {
        get
        {
            return supplierItems;
        }
        private set
        {
            if (supplierItems == value)
            {
                return;
            }
            supplierItems = value;
            OnPropertyChanged("SupplierItems");
        }
    }
    public SupplierItem CurrentSupplier
    {
        get
        {
            if (m_SuppliersView != null)
            {
                return m_SuppliersView.CurrentItem as SupplierItem;
            }

            return null;
        }
    }
   private void OnCollectionViewCurrentChanged(object sender, EventArgs e)
    {
// view model is inherited from a base class.  base method listed below
        OnPropertyChanged("CurrentSupplier");   
    }

   protected virtual void OnPropertyChanged(string propertyName)
    {
        VerifyPropertyName(propertyName);

        var handler = PropertyChanged;
        if (handler != null)
        {
            var e = new PropertyChangedEventArgs(propertyName);
            handler(this, e);
        }
    }

    private void Load() // Load event to populate the treeview source object
    { 
// SupplierItems object is populated just fine and treeview displays just fine so I won't show how the sausage is made.   I believe the issue is here:  
        m_SuppliersView = CollectionViewSource.GetDefaultView(SupplierItems);

        if (m_SuppliersView != null)
        {
            m_SuppliersView.CurrentChanged += OnCollectionViewCurrentChanged;
        }

        OnPropertyChanged("CurrentSupplier");
xaml中的

<Window.Resources>
       <HierarchicalDataTemplate x:Key="SuppiersDistributorsTemplate" ItemsSource="{Binding Children}">
          <TextBlock Text="{Binding ManagedLocationName}"/>
       </HierarchicalDataTemplate>
</Window.Resources>


<TreeView x:Name="tvSuppliers" ItemsSource="{Binding SupplierItems}" 
          ItemTemplate="{StaticResource SuppiersDistributorsTemplate}" 
          SelectedValuePath="CurrentSupplier">              
</TreeView>

对此有何看法?
当我在方法“OnCollectionViewCurrentChanged”中设置断点时,单击树视图节点时什么也没发生。即“CurrentSupplier”永远不会更新,所以我不能在另一种方法中使用CurrentSupplier(为另一个控件加载一个集合)。

由于

1 个答案:

答案 0 :(得分:1)