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

3

我正在尝试在样式中设置附加属性,我希望使用它们来附加行为。然而,我无法让它起作用。 以下是代码:

附加属性

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>


你尝试过加上括号吗 (test:TestBehaviour.Test) - Pragmateek
1
@Pragmateek 刚刚尝试了一下。无法编译((test未声明命名空间),也尝试了“(TestBehaviout.Test)”)。 - Martin Chudoba
1个回答

5

附加属性的所有者类型必须是声明它的类,这里是TestBehaviour,而不是Grid。请将声明更改为:

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

请参阅MSDN文档RegisterAttached

ownerType - 注册依赖属性的所有者类型


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