代码之家  ›  专栏  ›  技术社区  ›  oscarkuo

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

  •  12
  • oscarkuo  · 技术社区  · 16 年前

    我尝试了附加属性和样式触发器,希望了解更多关于它的信息。 我写了一个非常简单的WPF Windows应用程序,附带属性:

      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>
    

    但是,我一直得到以下编译错误:

    错误MC4003:无法解析Style属性“something”。请验证所属类型是样式的TargetType,或者使用Class.Property语法指定属性。第10行,位置29。

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

    1 回复  |  直到 13 年前
        1
  •  17
  •   Tim Cooper    13 年前

    依赖项属性的支持方法命名不正确,必须是静态的:

    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 NS映射中指定程序集,因为该命名空间位于当前程序集中。改为这样做:

    xmlns:local="clr-namespace:TestStyleTrigger"