繁体   English   中英

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

[英]Set custom attached property in style setter

我试图在一个样式中设置附加属性,我想用它们来附加行为。 但是我无法让它发挥作用。 继承人代码:

附属物

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>

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

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

有关RegisterAttached的信息,请参阅MSDN文档:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM