我试图从我的 TreeView 中获取选定的项目,但遇到了一些问题。
我正在关注 MVVM 架构。我的 ViewModel 包含我的模型中的一个类的集合。所以我已经将 TreeView 的 ItemSource 与该集合绑定了。我想将 TreeView 的 selectedItem 绑定到绑定集合的项目。我怎么做?这是 SelectedItem 和 IsSelected 属性的代码。
private static sourceData _selectedItem = null;
/// <summary>
/// Selected Item in the tree
/// </summary>
public static sourceData SelectedItem
{
get { return _selectedItem; }
set
{
if (_selectedItem != value)
{
_selectedItem = value;
}
}
}
private bool _isSelected;
/// <summary>
/// Get/Set for Selected node
/// </summary>
public bool IsSelected
{
get { return _isSelected; }
set
{
if (_isSelected != value)
{
_isSelected = value;
if (_isSelected)
{
SelectedItem = this;
OnPropertyChanged("IsSelected");
}
}
}
}
/// <summary>
/// Property changed event
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Property changed event handler
/// </summary>
/// <param name="propertyName"></param>
protected virtual void OnPropertyChanged(string propertyName)
{
var handler = this.PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
当我调试它时,int SelectedItem = this;
'this' 指针包含我的树视图绑定到的集合。我需要有一个 SelectedDataSource 以便我可以将它分配给选定的项目。如何让我的 TreeView 将集合中的 selectedItem 返回给我?
仅供参考,这是我的 TreeView 的 XAML 代码
<TreeView Margin="5,0,0,0" ItemsSource="{Binding SourceData}" Width="390">
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="IsSelected" Value="{Binding DataContext.IsSelected, Mode=TwoWay, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" />
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu Name="contextMenu" DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}" >
<MenuItem Name="menuItem" Header="Rename" Command="{Binding RenameCommand}" />
</ContextMenu>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
</Trigger>
</Style.Triggers>
</Style>
</TreeView.ItemContainerStyle>
PS:如果我在我的模型中编写上面的代码,我会得到一切正常工作。但是我不能在Model中编写上面的代码,它必须在VM中。