Updating Custom Attached Property in Style Trigger with Setter
Asked Answered
G

1

13

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?

Grotto answered 10/4, 2009 at 0:2 Comment(0)
P
19

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"
Passed answered 10/4, 2009 at 9:18 Comment(1)
I 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). +1Ulises

© 2022 - 2024 — McMap. All rights reserved.