关于#c##的问题:wpf 使用winform中的propertyGrid控件输入内容时,文本框中原本的内容会清空(操作系统-windows)

wpf 使用winform中的propertyGrid控件输入内容时,文本框中原本的内容会清空,这是为什么?

下面是wpf引用winform的代码

      xmlns:wfi ="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
      xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms")

   <wfi:WindowsFormsHost  Width="400" Height="300">
   <wf:PropertyGrid ToolbarVisible="False" HelpVisible="False" x:Name ="propertyGrid"></wf:PropertyGrid >
   </wfi:WindowsFormsHost >

img

这是因为 WPF 和 WinForms 是两个不同的UI框架,它们对控件状态的管理方式不同造成的。
在 WinForms 中,当焦点离开一个控件时,它的内容会被保存。而在 WPF 中,当焦点离开一个控件时,它的内容会被清空。
所以在你的代码中,当 PropertyGrid 控件获取焦点时,文本框中的内容被清空。这是 WPF 的默认行为。
要解决这个问题,你有两种方法:

  1. 在文本框失去焦点时手动保存其内容。例如:
    xml csharp private void TextBox_LostFocus(object sender, RoutedEventArgs e) { TextBox textBox = sender as TextBox; textBox.Tag = textBox.Text; } 然后在文本框重新获取焦点时,从 Tag 属性中恢复内容: xml csharp private void TextBox_GotFocus(object sender, RoutedEventArgs e) { TextBox textBox = sender as TextBox; textBox.Text = textBox.Tag as string; }
  2. 禁用 WPF 的默认行为,使文本框中的内容在失去焦点时不清空。可以这样设置:
    xml

向文本框输入信息时文本框会清空而且不能连续输入,(比如 输入1、2、3时,只会单独出现一个字符,上一个字符会消失),光标的得到和失去对文本框内容没有影响