WindowsFormsHost和DependencyProperty

时间:2010-04-22 19:24:18

标签: wpf binding prism windowsformshost dependency-properties

我有一个Windows窗体控件,我试图使用 WindowsFormsHost 类包装为WPF控件;我想将遗留控件绑定到视图模型。具体来说,控件公开了一个网格属性 GridVisible ,我想将视图模型绑定到。我使用私有静态支持字段和静态只读属性来表示依赖项属性(功能上与静态,公共字段相同,但更少混乱)。当我尝试通过XAML设置控件的 GridVisible 属性时,它不会更新。想法?我做错了什么?

DrawingHost类

/// <summary>
/// Provides encapsulation of a drawing control.
/// </summary>
public class DrawingHost : WindowsFormsHost
{
    #region Data Members

    /// <summary>
    /// Holds the disposal flag.
    /// </summary>
    private bool disposed;

    /// <summary>
    /// Holds the grid visible property.
    /// </summary>
    private static readonly DependencyProperty gridVisibleProperty =
        DependencyProperty.Register("GridVisible", typeof(bool),
        typeof(DrawingHost), new FrameworkPropertyMetadata(false,
            FrameworkPropertyMetadataOptions.AffectsRender |
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

    /// <summary>
    /// Holds the pad.
    /// </summary>
    private readonly DrawingPad pad = new DrawingPad();

    #endregion

    #region Properties

    /// <summary>
    /// Get or set whether the grid is visible.
    /// </summary>
    public bool GridVisible
    {
        get { return (bool)GetValue(GridVisibleProperty); }
        set { SetValue(GridVisibleProperty, pad.GridVisible = value); }
    }

    /// <summary>
    /// Get the grid visible property.
    /// </summary>
    public static DependencyProperty GridVisibleProperty
    {
        get { return gridVisibleProperty; }
    }

    #endregion

    /// <summary>
    /// Default-construct a drawing host.
    /// </summary>
    public DrawingHost()
    {
        this.Child = this.pad;
    }

    /// <summary>
    /// Dispose of the drawing host.
    /// </summary>
    /// <param name="disposing">The disposal invocation flag.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && !disposed)
        {
            if (pad != null)
            {
                pad.Dispose();
            }
            disposed = true;
        }
        base.Dispose(disposing);
    }
}


XAML

<UserControl x:Class="Drawing.DrawingView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
mc:Ignorable="d" 
xmlns:local="clr-namespace:Drawing">
<local:DrawingHost GridVisible="True"/></UserControl>

1 个答案:

答案 0 :(得分:1)

依赖属性的第一个规则之一是除了GetValueSetValue调用之外,从不在get和set中包含任何逻辑。这是因为当它们在XAML中使用时,它们实际上并不通过get和set访问器。它们与GetValueSetValue调用内联。所以你的代码都不会被执行。

执行此操作的适当方法是使用PropertyMetadata方法中的DependencyProperty.Register参数设置回叫。然后在回调中,您可以执行任何额外的代码。