WPF 与 WinForms 互操作及控件问题

整理 WPF 中引用 WinForm 控件、PropertyGrid 使用、ListView 样式和 WindowsFormsHost 常见问题。

1. 在 WPF 中引用 WinForm 控件

1.1 在 XAML 中使用

首先,添加对 System.Windows.Forms.dll 和 WindowsFormsIntegration.dll 的引用。

然后在 XAML 文件中添加以下命名空间:

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

最后使用 WinForm 控件时要这么写:

<wfi:WindowsFormsHost>
    <wf:PropertyGrid x:Name="propertyGrid"/>
</wfi:WindowsFormsHost>

1.2 在代码中使用

首先,添加对 System.Windows.Forms.dll 的引用。

使用时推荐直接写出完整的命名空间,避免和 WPF 控件的命名空间冲突造成不明确的引用:

System.Windows.Forms.PropertyGrid propertyGrid = new System.Windows.Forms.PropertyGrid();

2. 使用 PropertyGrid 的小技巧

要在 PropertyGrid 中显示某个对象的属性,只需设置 PropertyGrid 的 SelectedObject 属性即可。

此时在 PropertyGrid 控件中显示的属性是指定对象的所有属性及其值。

设置属性的“可见”特性:

// 指定某一属性或事件是否应在“属性”窗口中显示。
[Browsable(false)]
public string SomeProperties { get; set; }

设置属性的描述信息:

// 指定属性或事件的描述。
[DescriptionAttribute("属性的描述信息")]
public string SomeProperties { get; set; }

设置属性的显示名称:

// 指定属性、事件或不采用任何参数的公共 void 方法的显示名称。
[DisplayNameAttribute("属性的显示名称")]
public string SomeProperties { get; set; }

设置属性的只读特性:

// 指定某个属性是否只能在设计时设置。
[DesignOnlyAttribute(true)]
public string SomeProperties { get; set; }

对属性进行分组:

// 指定当属性或事件显示在一个设置为“按分类顺序”模式的
// PropertyGrid 控件中时,用于对属性或事件分组的类别的名称。
// 在分组名称前加 "\t" 可以提高分组显示顺序,并且不会显示制表符。
[CategoryAttribute("分组名称")]
public string SomeProperties { get; set; }

3. ListView 的 GridView 视图下 UpperHighlight 矩形问题

ListView 设置 View 为 GridView 时,选中与鼠标悬停条目上部分会有一个名为 UpperHighlight 的矩形,可能会导致 UI 视觉问题。

解决方式是重写 ListViewItem 的 ControlTemplate:

<Style TargetType="ListViewItem">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="ListViewItem">
        <Border CornerRadius="2" SnapsToDevicePixels="True" BorderThickness="{TemplateBinding BorderThickness}"
                BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}">
          <GridViewRowPresenter VerticalAlignment="{TemplateBinding VerticalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
        </Border>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

4. WindowsFormsHost 不显示

在 WPF 中加载 WinForm 控件,如果 WPF 窗体内所有的 WinForm 控件都不显示,则检查 WPF 窗口 AllowsTransparency 是否为 False;如果有个别 WinForm 控件不显示,则可能是控件绘制时异常导致,具体问题具体分析。

5. WPF 鼠标移动到窗口外抬起,窗口无法收到事件

解决方法:在 MouseDown 事件中调用 CaptureMouse,在 MouseUp 事件中调用 ReleaseMouseCapture。

❤️ 如果这篇文章对你有帮助,欢迎赞助支持我继续维护 ❤️

☕ Support me ⚡ 爱发电赞助