我可以在Windows用户控件上添加DependencyProperty吗?

时间:2012-02-22 08:26:01

标签: wpf data-binding .net-4.0 user-controls

我正在尝试在WPF应用程序中托管Visio ActiveX对象。

为此,我创建了一个Windows用户控件项目,我在其中添加了Visio对象。然后,此Windows用户控件将托管在WindowsFormsHost对象中的WPF用户控件上。

<WindowsFormsHost Name="wfHost" Grid.Row="1">
    <wf:VisioUserControl FileNamePath="?"/>
</WindowsFormsHost>

我想要做的是将 FileNamePath 成员的值绑定到定义路径的 TextBox 元素的值。

该项目遵循MVVM模式,因此我无法访问ViewModel中的 VisioUserControl 对象。

我正在考虑的解决方案是将 FileNamePath 成员绑定到包含路径的 TextBox 的值,但它不是 DependencyProperty < / em>似乎我无法在windows用户控件的代码中定义一个。

那么,有没有解决方法来执行此绑定?

提前致谢。

3 个答案:

答案 0 :(得分:7)

您可以通过创建包裹UserControl的{​​{1}}来解决此问题(我写了simple tutorial on UserControl creation here)。然后,您可以向VisioUserControl添加FileNamePath依赖项属性。在此依赖项属性的属性更改处理程序中,在此用户控件包装的UserControl上设置FileNamePath属性。

答案 1 :(得分:2)

好的我已经创建了一个托管Winforms控件的WPF用户控件的示例,其中包含一个绑定到winforms控件的text属性的依赖项属性。

 public partial class ActiveXObjectHoster : UserControl
{
    private static System.Windows.Forms.Label testObject;
    public ActiveXObjectHoster()
    {
        InitializeComponent();
        testObject = new System.Windows.Forms.Label();
        windowsFormsHost1.Child = testObject;
    }

    #region Properties
    public static DependencyProperty FileNameProperty = DependencyProperty.Register("FileName", typeof(string), typeof(ActiveXObjectHoster), new UIPropertyMetadata("",new PropertyChangedCallback(OnFileNamePropertyChanged)));


    public string FileName
    {
        get { return (string)GetValue(FileNameProperty); }
        set
        {
            SetValue(FileNameProperty, value);
        }
    }


    private static void OnFileNamePropertyChanged(
DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        testObject.Text = (string)e.NewValue;
    }


    #endregion
}

这是控件的xaml(非常简单)

<UserControl xmlns:my="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"  
         x:Class="WPFTestApp2.Controls.ActiveXObjectHoster"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         x:Name="ObjectHost"
         Height="100" Width="100">
    <Grid>
           <my:WindowsFormsHost x:Name="windowsFormsHost1" />
    </Grid>
</UserControl>

您需要做的是将测试对象从Label更改为您正在使用的任何Visio对象。然后在属性回调中将text属性更改为文件名或您想要的任何属性。

如上所述,这是在后面的代码中完成的,但对于用户控件来说很好,它与使用它的任何东西完全分离,你只需要绑定到filename的属性控制。

Here is a link到我创建的项目,显示如何使用控件。有一个文本框,其文本绑定到FileName属性,该属性更改Winforms标签文本。

如果您想在winforms中使用它,可以将其置于Winforms Usercontrol中(就像您在回复我的评论时提到的那样)

尝试更换控件的标签,看看它是否有效。

答案 2 :(得分:0)

为什么不实现UserControl来包装WindowsFormHost和Visio用户控件?然后你可以添加一个Dependency属性,并在PropertyChangedCallback的处理程序后面的代码中实现,并适当地与WinForms控件交互