0

In my WPF C# project, I've created a TreeView. Each TreeViewItem has a LostFocus event that must be raised when item lost its focus. I've also create a button that is needed to be clicked when user wants to change header of a certain TreeViewItem. User, after the selection in TreeView, can click on button and a TextBox appear replacing the TreeViewItem header. If user does not click on TextBox but click on another TreeViewItem, the LostFocus event is never raised. Otherwise, if user click on TextBox and then change focus, it is raised. I've also used textBox.Focus() and Keyboard.Focus(textBox) but the do not work. How can I fix this?

Just to be clear, before creating a post I've read another SO answer here

Here is the snippet code

 private void RenameButton_Click(object sender, RoutedEventArgs e)
     {

         TreeViewItem twItemSelected = (TreeViewItem)this.Treeview_PropertyDefinition.SelectedItem;                                                            
         var textBox = new TextBox()
         {
             Text = (String)twItemSelected.Header,
         };
         textBox.Focus();
         Keyboard.Focus(textBox);
         if (textBox.IsFocused)
             MessageBox.Show("focused");


         twItemSelected.Header = textBox;            


         //check which property is currently selected

             String parentName = ((TreeViewItem)twItemSelected.Parent).Name;
          ((TreeViewItem)twItemSelected.Parent).Parent).Name;

            //get values from file 
            //show page based on parent value
             switch (parentName)
             {
                 case "RectangleBar_TreeviewItem":
                     textBox.LostFocus += (o, ev) =>
                     {...}  
    }
4

1 回答 1

3

请原谅我这么说,但每一个读过你的问题的普通 WPF 用户都可能同情地摇头。我们为您感到难过,因为您还没有学习真正的“WPF 之禅”,它利用数据绑定、模板和触发器来使您的 UI 动态化,而不是以老式的方式进行。由于这种能力,WPF 很漂亮。它还使事情“1000%”更容易。

我建议您更改 UI 以在 TreeViewItem 上使用触发器来根据您在 TreeViewItem 中定义的属性替换 HeaderTemplate。双击项目时将此属性设置为 true。当 IsKeyboardFocusWithin 变为 false 时将其设置为 false(您可以覆盖元数据并为此添加 PropertyChangedCallback)。

就您的LostFocus问题而言,我怀疑您的问题是您有多个焦点范围。

有关以“WPF 方式”执行此操作的其他详细信息

以下是有关如何使用附加属性、触发器和模板来实现此功能的一些详细信息。

您的模板可以根据需要简单或复杂。这里很简单:

<DataTemplate x:Key="NormalTemplate">
  <ContentPresenter />
</DataTemplate>

<DataTemplate x:Key="TextBoxTemplate">
  <TextBox Text="{Binding}" />
</DataTemplate>

以下是您的风格:

可以使用“propa”片段在 MyWindowClass 中创建附加属性“ShowTextBox” - 只需键入“propa”并点击选项卡,然后填写空白。

要切换项目以显示文本框,只需:

SetShowTextBox(item, true);
To switch it back:

SetShowTextBox(item, false);

请尝试学习和投资于模式和实践,WPF以便轻松实现您想要实现的目标。

还有一些项目可以帮助您开始使用 TreeViews 实现的目标。

示例项目

于 2014-04-11T16:51:14.770 回答