代码之家  ›  专栏  ›  技术社区  ›  Martin Chudoba

在样式设置器中设置自定义附加属性

  •  3
  • Martin Chudoba  · 技术社区  · 11 年前

    我试图在样式中设置附加属性,我想使用它们来附加行为。然而,我无法让它发挥作用。 以下代码:

    附加属性

    public class TestBehaviour
    {
        public static bool GetTest(Grid grid)
        {
            return (bool)grid.GetValue(TestProperty);
        }
    
        public static void SetTest(Grid grid, bool value)
        {
            grid.SetValue(TestProperty, value);
        }
    
        public static readonly DependencyProperty TestProperty = DependencyProperty.RegisterAttached("Test", typeof(bool), typeof(Grid));
    
    }
    

    Xaml公司

    <Window x:Class="AttachedPropertyTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:test="clr-namespace:AttachedPropertyTest"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.Style>
            <Style TargetType="Grid">
                <Setter Property="test:TestBehaviour.Test" Value="true"></Setter>
            </Style>
        </Grid.Style>
    </Grid>
    

    1 回复  |  直到 11 年前
        1
  •  5
  •   Clemens    11 年前

    附加属性的所有者类型必须是声明该属性的类,即 TestBehaviour 这里,不是 Grid .将声明更改为:

    public static readonly DependencyProperty TestProperty =
        DependencyProperty.RegisterAttached("Test", typeof(bool), typeof(TestBehaviour));
    

    请参阅MSDN文档以了解 RegisterAttached :

    所有者类型 -正在注册依赖项属性的所有者类型