WPF附加依赖属性计算字段更新

时间:2012-07-06 11:29:36

标签: wpf attached-properties

给定一个非常简单的自定义容器控件CustomDock,其中包含两个附加属性IsFooBar1和IsFooBar2。如果设置IsFooBar2在更改时更新IsFooBar1的值,我如何确保visual studio将更新生成的xaml以获取IsFooBar1的值。

自定义控件:

    public class CustomDock : DockPanel
    {
    public static readonly DependencyProperty IsFooBarProperty1 = DependencyProperty.RegisterAttached(
      "IsFooBar1",
      typeof(Boolean),
      typeof(CustomDock),
      new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)
    );

    public static void SetIsFooBar1(UIElement element, Boolean value)
    {
        element.SetValue(IsFooBarProperty1, value);
    }

    public static Boolean GetIsFooBar1(UIElement element)
    {
        return (Boolean)element.GetValue(IsFooBarProperty1);
    }

    public static readonly DependencyProperty IsFooBarProperty2 = DependencyProperty.RegisterAttached(
      "IsFooBar2",
      typeof(Boolean),
      typeof(CustomDock),
      new PropertyMetadata(false)
    );

    public static void SetIsFooBar2(UIElement element, Boolean value)
    {
        element.SetValue(IsFooBarProperty2, value);
        element.SetValue(IsFooBarProperty1, value);

    }

    public static Boolean GetIsFooBar2(UIElement element)
    {
        return (Boolean)element.GetValue(IsFooBarProperty2);
    }

}

它在xaml中的用法:

<Window x:Class="TestAttachedIndirectProperties.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525" xmlns:my="clr-namespace:TestAttachedIndirectProperties">
<Grid>
    <my:CustomDock Height="100" HorizontalAlignment="Left" Margin="138,123,0,0" x:Name="customDock1" VerticalAlignment="Top" Width="200">
        <Button Content="Button" Height="23" Name="button1" Width="75" my:CustomDock.IsFooBar1="True" my:CustomDock.IsFooBar2="True" />
    </my:CustomDock>
</Grid>

在Visual Studio设计期间,如果IsFooBar2更改为false,则IsFooBar1也应该被赋予false值,但不是在属性窗格或xaml代码中。

1 个答案:

答案 0 :(得分:1)

WPF不保证你的Dependency属性setter会被调用(就像那个一样奇怪)如果你想设置依赖属性你需要这样做我通过属性定义注册一个OnPropertyChanged回调并将cascade逻辑放在那里