سؤال

Would it be possible for an Adorner to be hidden / displayed depending on the value of a property in a class ?

Should I use attached properties for this purpose ?

If so, how exactly can the Adorner's visibility be controlled; do I have to manually remove it / add it to the Adorner Layer within the Dependency Object's OnChanged event ?

This is just a very quick code representation of what I'm trying to do:

(Note: I'm not even sure if its the right way of doing things. I want the Adorner's visibility to be controlled by the value of a property that is modified by the code in my business model. The problem with Attached Properties is that its the control's responsibility to update the value of the property instead of the code in my business domain.)

public static class IsValidBehavior
{
    public static readonly DependencyProperty IsValidProperty = DependencyProperty.RegisterAttached("IsValid",
                                                                    typeof(bool),
                                                                    typeof(IsValidBehavior),
                                                                    new UIPropertyMetadata(false, OnIsValidChanged));

    public static bool GetIsValid(DependencyObject obj)
    {
        return (bool)obj.GetValue(IsValidProperty);
    }
    public static void SetIsValid(DependencyObject obj, bool value)
    {
        obj.SetValue(IsValidProperty, value);
    }

    private static void OnIsValidChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
    {
        UIElement element = dependencyObject as UIElement;

        if (element == null)
            return;

        if ((bool)e.NewValue == true)
        {
            // Display the Adorner
        }
        else
        {
            // Hide the Adorner
        }
    }
}
هل كانت مفيدة؟

المحلول

Well, if I right understood your question, in WPF you have 2 ways to do that, from code or from XAML. From code, you more or less already did, in XAML you can do something like this, I think:

Visibility="{Binding Path=MyVisibilityVariant, 
       Converter={StaticResource VisibilityConverter}}

In other words bind it to some property. My general suggestion: is use XAML whenever you can, considering a couple of variants:

  • XAML declaration makes the software very scallable, but also more complex (consider your, or your group cappabilities, somehow doing the stuff in code behind is best, if not only solution available)

  • Consider you deadlines, cause on XAML stuff implementing/debugging/fixing you will spend more time then on code.

EDIT

Defining custom Adorder in order to be able to define it in XAML

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top