0

给定一个非常简单的自定义容器控件 CustomDock,带有两个附加属性 IsFooBar1 和 IsFooBar2。如果设置 IsFooBar2 在更改 IsFooBar1 的值时更新了 IsFooBar1 的值,我如何确保 Visual Studio 将为 IsFooBar1 的值更新生成的 xaml。

自定义控件:

    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 代码中都不是。

4

1 回答 1

1

WPF 不保证将调用您的 Dependency 属性设置器(这很奇怪),如果您想设置依赖属性,您需要通过属性定义注册 OnPropertyChanged 回调并将级联逻辑放在那里。

于 2012-07-06T11:40:19.450 回答