65.9K
CodeProject 正在变化。 阅读更多。
Home

将 WPF UserControls 集成到 WinForms 中

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.95/5 (15投票s)

2008年5月23日

CPOL

1分钟阅读

viewsIcon

96836

downloadIcon

4579

关于将 WPF UserControls 嵌入 WinForms 的文章

引言

在之前的文章中,作者介绍了如何将 WinForms 控件嵌入到 WPF 中。本文介绍了相反的操作:如何将 WPF 用户控件集成到 WinForms 中。 在示例中,一个可缩放的 WPF 图像被托管在一个 WinForms 对话框中。

概念

要在 WinForms 中托管 WPF 用户控件,可以使用位于 System.Windows.Forms.Integration 命名空间中的 ElementHost 控件。 此控件具有一个名为 Child 的属性,可以将 UIElement 的实例分配给该属性。

项目

这是我们的 ScaleableImageControl 的 XAML。它非常简单,只是一个带有 BitmapEffect 的图像。

<UserControl x:Class="ScaleableImageControl.ScaleableImageCtrl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="300" Width="300">

        <Image Margin="10" x:Name="img" Stretch="Uniform" Opacity="1">
            <Image.BitmapEffect>
                <DropShadowBitmapEffect Opacity="1" />

            </Image.BitmapEffect>
        </Image>

</UserControl>

现在,我们向用户控件添加两个方法,这些方法将从 Windows Forms 对话框中调用。

public void SetSource(string fileName)
{
    img.Source = new BitmapImage(new Uri(fileName));
}

public void SetOpacity(double opacity)
{
    img.Opacity = opacity;
}

我们可以使用此接口设置透明度和显示的图像。

在 WinForms 中托管 WPF 控件

在 VS 2008 的设计器中打开 Winforms 对话框时,您会发现工具箱中有一个 ScaleableImageControl。

WPF_Winforms_2.jpg

您可以将其拖动到您的 Winforms 对话框中。 将为您创建一个 ElementHost 实例和一个 ScaleableImageControl 实例,并将 ScaleableImageControl 对象分配给 ElementHost 对象的 Child 属性。 VS 2008 在这里帮了我们很大的忙。 最后,我们需要一些控件来与 ScaleableImageControl 对象交互(分配图像和设置透明度)。

WPF_Winforms_3.jpg

这是交互代码:

private void udOpacity_ValueChanged(object sender, EventArgs e)
{
    scaleableImageCtrl1.SetOpacity( (double) udOpacity.Value);
}

private void btnBrowse_Click(object sender, EventArgs e)
{
    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        try
        {
            scaleableImageCtrl1.SetSource(openFileDialog1.FileName);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

将 WPF 集成到 Winforms 中并不难。 试试看,项目已附上。 玩得开心!

© . All rights reserved.