在样式触发器中使用Setter更新自定义附加属性

12

我正在尝试使用附加属性和样式触发器,希望能更好地了解它。 我编写了一个非常简单的 WPF 窗口应用程序,其中包含一个附加属性:

  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);
  }

我尝试使用在按钮样式部分定义的属性触发器更新“Something”附加属性:

  <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>

然而,我一直收到以下编译错误:

error MC4003:无法解析样式属性“Something”。请验证所有者类型是否为样式的TargetType,或使用Class.Property语法指定属性。第10行第29个位置。

我不明白为什么会出现这个错误,因为我确实在 section中的 标签中使用了“Class.Property”语法。有人能告诉我如何修复这个编译错误吗?

1个回答

18

你的依赖属性的后备方法命名不正确,必须是静态的:

public static int GetSomething(DependencyObject d)
{
    return (int)d.GetValue(SomethingProperty);
}

public static void SetSomething(DependencyObject d, int value)
{
    d.SetValue(SomethingProperty, value);
}

此外,在XAML中的本地XML命名空间映射中不应该指定程序集,因为该命名空间在当前程序集中。改为这样做:

xmlns:local="clr-namespace:TestStyleTrigger"

我已经有了一个完全静态的类来处理我的AttachedProperty,也有正确的Get和Set方法。虽然我遇到了与OP完全相同的异常,但是通过在命名空间中删除程序集规范(在我的情况下是由ReSharper自动添加的),也可以解决这个问题。+1 - LuckyLikey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接