TreeView控件不像ListBox或者ComboBox这些可以绑定SelectedItem
我们可以通过TreeView的SelectedItemChanged事件来进行获取
View中的代码:
<TreeView x:Name="myTreeView" Margin="2" BorderThickness="1" ItemsSource="{Binding TreeViewNodes}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectedItemChanged">
<i:InvokeCommandAction Command="{Binding Path=TreeNodeSelectedCommand}" CommandParameter="{Binding ElementName=myTreeView, Path=SelectedItem}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Nodes}">
<TextBlock Text="{Binding Text}" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
ViewModel中的代码:
public ViewModel()
{
TreeNodeSelectedCommand = new DelegateCommand<object>(SelectNode);
}
private ObservableCollection<TreeViewNode> m_treeViewNodes = new ObservableCollection<TreeViewNode>();
public ObservableCollection<TreeViewNode> TreeViewNodes
{
get => m_treeViewNodes;
set => SetProperty(ref m_treeViewNodes, value);
}
public DelegateCommand<object> TreeNodeSelectedCommand {
get; set; }
private async void SelectNode(object selectedItem)
{
// 这样就可以获取到用户所选中的节点了
var currentNode = selectedItem as TreeViewNode;
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/35087.html