【问题标题】:Editing item in TreeView by ContextMenu or HotKey通过 ContextMenu 或 HotKey 在 TreeView 中编辑项目
【发布时间】:2016-04-25 13:36:39
【问题描述】:

我想在两种情况下启用TreeView 中的项目编辑:

  • 当用户在ContextMenuTreeView 中单击Edit 按钮时
  • 当用户在 TreeView 的选中项上单击F2 时。

我的TreeView:

<TreeView ItemsSource="{Binding FooColl}" >
    <TreeView.Resources>
        <DiscreteObjectKeyFrame x:Key="proxy" Value="{Binding}"/>
            <HierarchicalDataTemplate DataType="{x:Type treeViewModel:NodeViewModel}" 
                                                     ItemsSource="{Binding Children}">
                <StackPanel Orientation="Horizontal">
                    <Image Source="treeNode.png" />
                    <TextBlock Text="{Binding FooValue}">
                    <TextBlock.ContextMenu>                                
                      <ContextMenu>
                          <MenuItem Header="Edit"/>
                      </ContextMenu>
                     </TextBlock.ContextMenu>
                    </TextBlock>
                </StackPanel>
            </HierarchicalDataTemplate>
    </TreeView.Resources>
</TreeView>

我的第一个想法是在HierarchicalDataTemplate 中使用TextBox 而不是TextBlock。但是,TextBox 的编辑模式是由MouseClick 启用的。因此,这不是我想要的。

对我该怎么做有什么想法吗?

【问题讨论】:

  • 你可以使用 IsReadOnly 属性吗?默认情况下它是假的,当用户点击编辑时,你把它变成真
  • @Amine 是的,我可以使用IsReadonly

标签: c# wpf mvvm treeview


【解决方案1】:

您可以使用 IsReadOnly 属性:

<TextBlock Text="{Binding FooValue}" IsReadOnly="{Binding ImReadOnly}">

要处理 F2 按键,你可以试试这个:

    public partial class MyView : UserControl
    {
        public MyView()
        {
            InitializeComponent();

            this.KeyDown += new KeyEventHandler(KeyDownEvent);
        }

        private void KeyDownEvent(object sender, KeyEventArgs e)
        {
            try
            {
                switch (e.Key)
                {
                    case Key.F2:
                        var vm = this.DataContext as YourViewModel;
                        vm.YourCommand.Execute(null);
                        break;
                }
            }
            catch (Exception ex)
            {
                //...
            }
        }
    }

【讨论】:

  • 我该如何在我的 viewModel 中处理这个问题?
  • 您可以从后面的代码中调用 Command。 var vm = this.DataContext as YourViewModel; vm.YourCommand.Execute(null);
  • 请把你的 cmets 写成答案,我会标记它。谢谢。:)
猜你喜欢
  • 2019-06-20
  • 1970-01-01
  • 1970-01-01
  • 2015-09-13
  • 2017-01-20
  • 1970-01-01
  • 2019-10-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多