Updating Custom Attached Property in Style Trigger with Setter
Your backing methods for the dependency property are named incorrectly and must be static:
public static int GetSomething(DependencyObject d)
{
return (int)d.GetValue(SomethingProperty);
}
public static void SetSomething(DependencyObject d, int value)
{
d.SetValue(SomethingProperty, value);
}
Also, you shouldn't specify the assembly in the local XML NS mapping in the XAML because the namespace is in the current assembly. Do this instead:
xmlns:local="clr-namespace:TestStyleTrigger"
oscarkuo
Updated on June 27, 2022Comments
-
oscarkuo about 2 years
I was trying out attached properties and style triggers hoping to learn more about it. I wrote a very simple WPF windows app with an attached property:
public static readonly DependencyProperty SomethingProperty = DependencyProperty.RegisterAttached( "Something", typeof(int), typeof(Window1), new UIPropertyMetadata(0)); public int GetSomethingProperty(DependencyObject d) { return (int)d.GetValue(SomethingProperty); } public void SetSomethingProperty(DependencyObject d, int value) { d.SetValue(SomethingProperty, value); }
And I was trying to update the 'Something' attached property with a property trigger defined in the button style section:
<Window x:Class="TestStyleTrigger.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestStyleTrigger;assembly=TestStyleTrigger" Title="Window1" Height="210" Width="190"> <Window.Resources> <Style x:Key="buttonStyle" TargetType="{x:Type Button}"> <Style.Triggers> <Trigger Property="IsPressed" Value="True"> <Setter Property="local:Window1.Something" Value="1" /> </Trigger> </Style.Triggers> </Style> </Window.Resources> <Button Style="{StaticResource buttonStyle}"></Button> </Window>
However, I kept getting following compilation error:
error MC4003: Cannot resolve the Style Property 'Something'. Verify that the owning type is the Style's TargetType, or use Class.Property syntax to specify the Property. Line 10 Position 29.
I can't understand why it gives me this error because I did use the 'Class.Property' syntax in the tag of the section. Can any one tell me how can I fix this compilation error?
-
LuckyLikey about 7 yearsI had already a fully static lass for my AttachedProperty, also with the correct Get and Set. Though I had exactly the same exception as the OP, it can also be solved, by removing the assembly specification in the namespace (which in my Case was added automatically by ReSharper). +1