逻辑组合依赖项属性

Joe*_*arp 6 wpf dependency-properties c#-4.0

我正在使用C#4.0并创建了一个DependencyObject MyView.

在MyView中,我有两个DependencyProperties,PropA和PropB,两者都是布尔值.

我想要第三个DependencyProperty,PropC,也是一个bool,简单地说,应该总是给我(PropA || PropB).

  1. 完成此任务的最佳方法是什么?
  2. 我也在考虑让PropC成为一个只读的DependencyProperty,但是已经阅读了有关绑定到readonly dp的问题(使用MVVM的WPF ReadOnly依赖项属性)

Ric*_*key 0

链接的网页适用于一种不寻常的情况,即“推送”绑定。也就是说,尝试对只读属性进行单向源绑定,而不是对尝试绑定到它的另一个属性进行尝试。相比之下,如果您希望您的属性可以使用其他属性上的单向绑定表达式绑定到其他属性,那么您可以使用只读依赖属性,而不会出现任何问题。

编辑:

这是一个例子:

<Grid>
    <Grid.Resources>
        <local:MyObject x:Key="myObject" PropertyA="True" PropertyB="False"/>
    </Grid.Resources>
    <StackPanel DataContext="{StaticResource myObject}">
        <CheckBox IsChecked="{Binding PropertyA}"  Content="PropertyA"/>
        <CheckBox IsChecked="{Binding PropertyB}"  Content="PropertyB"/>
        <CheckBox IsChecked="{Binding PropertyC, Mode=OneWay}" IsEnabled="False"  Content="PropertyC"/>
    </StackPanel>
</Grid>
Run Code Online (Sandbox Code Playgroud)

以及依赖属性,其中之一是只读的:

public class MyObject : DependencyObject
{
    public bool PropertyA
    {
        get { return (bool)GetValue(PropertyAProperty); }
        set { SetValue(PropertyAProperty, value); }
    }

    public static readonly DependencyProperty PropertyAProperty =
        DependencyProperty.Register("PropertyA", typeof(bool), typeof(MyObject), new UIPropertyMetadata(false, OnPropertyAOrBChanged));

    public bool PropertyB
    {
        get { return (bool)GetValue(PropertyBProperty); }
        set { SetValue(PropertyBProperty, value); }
    }

    public static readonly DependencyProperty PropertyBProperty =
        DependencyProperty.Register("PropertyB", typeof(bool), typeof(MyObject), new UIPropertyMetadata(false, OnPropertyAOrBChanged));

    public bool PropertyC
    {
        get { return (bool)GetValue(PropertyCProperty); }
        set { SetValue(PropertyCPropertyKey, value); }
    }

    private static readonly DependencyPropertyKey PropertyCPropertyKey =
        DependencyProperty.RegisterReadOnly("PropertyC", typeof(bool), typeof(MyObject), new UIPropertyMetadata());
    public static readonly DependencyProperty PropertyCProperty = PropertyCPropertyKey.DependencyProperty;

    private static void OnPropertyAOrBChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var myObject = d as MyObject;
        myObject.PropertyC = myObject.PropertyA || myObject.PropertyB;
    }
}
Run Code Online (Sandbox Code Playgroud)