Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: Cannot Get Custom Attached Property to work as a Trigger Property

Tags:

c#

wpf

xaml

So I have a class that looks like this:

internal class MyClass
{
    public static readonly DependencyProperty IsSomethingProperty =
            DependencyProperty.RegisterAttached(
                "IsSomething", // property name
                typeof(bool), // property type
                typeof(MyClass), // owner type
                new FrameworkPropertyMetadata(false)
                );

    public static void SetIsSomething(DependencyObject obj, bool value)
    {
        obj.SetValue(IsSomethingProperty, value);
    }

    [AttachedPropertyBrowsableForType(typeof(TreeViewItem))]        
    public static bool GetIsSomething(DependencyObject obj)
    {
        return (bool)obj.GetValue(IsSomethingProperty);
    }
}

I would like to be able to use this attached property as a trigger property in a control template, like so:

<ControlTemplate TargetType="TreeViewItem">
    <!-- stuff here omitted for brevity -->
    <Trigger Property="my:MyClass.IsSomething" Value="True">
        <!-- setters for when IsSomething is True -->
    </Trigger>
</ControlTemplate>

(the above control template assumes the proper xmlns:my="clr-namespace:MyAssembly" where MyAssembly contains MyClass is in the enclosing XAML file)

Here's my trouble: when I do this, it compiles fine. However, when I try to see this control template in action in the designer, it complains Cannot find the 'IsSomething' template property on type 'System.Windows.Controls.TreeViewItem'. and the designer won't load.

I've tried the RegisterAttached override with MyClass as well as TreeViewItem as the owner type, neither fixes this. I've also tried it with and without the AttachedPropertyBrowsableForType attribute on GetIsSomething. Does anyone see what the problem is?

like image 271
FMM Avatar asked Sep 17 '25 09:09

FMM


1 Answers

Found the answer as soon as I posted the question. I'm posting the answer to help anyone who's run into the same issue. Mark your class public. Not sure if this is by design or not, but it seems they could at least improve the error message here.

Hope this helps someone.

like image 150
FMM Avatar answered Sep 20 '25 01:09

FMM