2

WindowsFormsHostクラスを使用してWPFコントロールとしてラップしようとしているWindowsフォームコントロールがあります。レガシーコントロールをビューモデルにバインドしたいと思います。具体的には、コントロールは、ビューモデルをバインドしたいグリッドプロパティ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>
4

1 に答える 1

1

GetValue依存関係プロパティの最初のルールの1つは、 andSetValue呼び出し以外のロジックをgetおよびsetに含めないことです。これは、XAMLで使用される場合、実際にはgetおよびsetアクセサーを経由しないためです。それらは、GetValueおよびSetValue呼び出しとインライン化されます。したがって、コードは実行されません。

PropertyMetadataこれを行う適切な方法は、メソッドのパラメーターを使用してコールバックを設定するDependencyProperty.Registerことです。次に、コールバックで追加のコードを実行できます。

于 2010-04-22T19:32:01.277 に答える