我有一个带有 ContextMenu 的 TreeView,其中包含添加/删除节点的选项。当我向树添加一个节点时,我当前正在向我的视图模型发送一个命令,该命令通过为显示树添加一个包装器和一个支持数据对象来处理添加请求。当我这样做时,我希望显示树中新创建的包装器成为树视图的选定项。我怎样才能做到这一点?我不知道如何从视图模型访问树视图,并怀疑您甚至不应该这样做。谢谢。
问问题
1105 次
2 回答
1
在 TreeViewItem 的 ViewModel 中,您有一个“IsSelected”属性,例如:
/// <summary>
/// Base class for all ViewModel classes displayed by TreeViewItems.
/// This acts as an adapter between a raw data object and a TreeViewItem.
/// </summary>
public class TreeViewItemViewModel : CoreViewModel
{
#region Data
private readonly ObservableCollection<TreeViewItemViewModel> _children;
private readonly TreeViewItemViewModel _parent;
private bool _isExpanded = false;
private bool _isSelected;
#endregion // Data
#region Constructors
#endregion // Constructors
#region Children
/// <summary>
/// Returns the logical child items of this object.
/// </summary>
public ObservableCollection<TreeViewItemViewModel> Children
{
get { return _children; }
}
#endregion // Children
#region HasLoadedChildren
#endregion // HasLoadedChildren
#region IsExpanded
/// <summary>
/// Gets/sets whether the TreeViewItem
/// associated with this object is expanded.
/// </summary>
public bool IsExpanded
{
get { return _isExpanded; }
set
{
if (value != _isExpanded)
{
_isExpanded = value;
OnPropertyChanged("IsExpanded");
}
// Expand all the way up to the root.
if (_isExpanded && _parent != null)
_parent.IsExpanded = true;
// Lazy load the child items, if necessary.
if (this.HasDummyChild)
{
this.Children.Remove(DummyChild);
this.LoadChildren();
}
}
}
#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;
OnPropertyChanged("IsSelected");
}
}
}
#endregion // IsSelected
然后在您的 XAML 中,您需要为 TreeViewItem 设置样式:
<TreeView.Resources>
<Style x:Key="TreeViewItemStyle" TargetType="{x:Type TreeViewItem}">
<Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
</Style>
</TreeView.Resources>
现在,您可以通过在新添加的项目中将 IsSelected 属性设置为 True 来设置 TreeView 的 SelectedItem。
于 2013-07-03T14:42:01.720 回答
-2
如果我了解您,您需要绑定到您的 SelectedItem。所以在你的 ViewModel 中创建:
private your_object_name _selectedItem;
public your_object_name SelectedItem
{
get { return _selectedItem; }
set
{
_selectedItem = value;
RaisePropertyChanged("SelectedItem");
}
}
在 TreeView 控件中的 XAML 代码中:
<TreeView SelectedItem="{Binding SelectedItem, Mode=TwoWay}" .../>
Mode=TwoWay
SelectedItem
允许您使用ViewModel 中的属性更改 TreeView 控件上的选择。
此致。
于 2013-07-02T20:46:34.607 回答