Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a read-only Boolean dependency property that returns `And` operation between two other dependency properties

How can I create a custom read-only Boolean dependency property that returns And operation between two custom Boolean dependency properties, for example (A, B),

And when A or B changes, I want the result property to trigger.

Any help to achieve that!

like image 680
Homam Avatar asked Nov 30 '25 17:11

Homam


1 Answers

Part 1: dependencies.

public static readonly DependencyProperty Source1Property =
    DependencyProperty.Register(
        "Source1",
        typeof(bool),
        typeof(MyControl),
        new FrameworkPropertyMetadata(false, new PropertyChangedCallback(UpdateTarget)));

public bool Source1
{
    get { return (bool)GetValue(Source1Property); }
    set { SetValue(Source1Property, value); }
}

void UpdateTarget(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    MyControl self = (MyControl)d;
    d.Target = d.Source1 && d.Source2;
}

Part 2: read-only

internal static readonly DependencyPropertyKey TargetPropertyKey =
    DependencyProperty.RegisterReadOnly(
        "Target",
        typeof(bool),
        typeof(MyControl),
        new PropertyMetadata(false));

public static readonly DependencyProperty TargetProperty =
    TargetPropertyKey.DependencyProperty;

public bool Target
{
    get { return (bool)GetValue(TargetProperty); }
    protected set { SetValue(TargetPropertyKey, value); }
}

Disclaimer: I didn't try the part 2.

Part 3:
if the source dependency properties are not defined by you, you can do the following trick:

DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty(
        MyControl.Source1Property,
        typeof(MyControl)));
if (dpd != null)
    dpd.AddValueChanged(this, UpdateTarget);
like image 152
Vlad Avatar answered Dec 03 '25 08:12

Vlad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!