在样式设置器中设置自定义附加属性 [英] Set custom attached property in style setter

查看:38
本文介绍了在样式设置器中设置自定义附加属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在样式中设置附加属性,我想用它们来附加行为.但是我无法让它工作.代码如下:

Im trying to set attached property inside a style, i want to use them to attach behaviour. However I cant get it to work. Heres code:

附加属性

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

}

XML

<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.将声明更改为:

The owner type of the attached property must be the class where it is declared, which is TestBehaviour here, not Grid. Change the declaration to:

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

有关 RegisterAttached,请参阅 MSDN 文档:

See the MSDN documentation for RegisterAttached:

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

ownerType - The owner type that is registering the dependency property

这篇关于在样式设置器中设置自定义附加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆