我有一个WindowsFormsHost控件,我试图使用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>发布于 2010-04-22 19:32:01
依赖属性的第一条规则之一是,除了GetValue和SetValue调用之外,永远不要在get和set中包含任何逻辑。这是因为当它们在XAML中使用时,它们实际上并不经过get和set访问器。它们内嵌着GetValue和SetValue调用。所以你的代码都不会被执行。
这样做的适当方法是使用PropertyMetadata方法中的DependencyProperty.Register参数设置一个回调。然后,在回调中,您可以执行任何额外的代码。
https://stackoverflow.com/questions/2693799
复制相似问题