【问题标题】:Set custom attached property in style setter在样式设置器中设置自定义附加属性
【发布时间】:2014-08-31 19:00:20
【问题描述】:

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

附加属性

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 刚刚尝试过。不会编译((测试未声明的命名空间)也试过“(TestBehaviout.Test)”

标签: wpf styles attached-properties


【解决方案1】:

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

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

请参阅 RegisterAttached 的 MSDN 文档:

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

【讨论】:

    猜你喜欢
    • 2011-08-26
    • 2011-11-23
    • 1970-01-01
    • 1970-01-01
    • 2013-06-26
    • 2020-09-04
    • 2022-07-13
    • 2013-01-25
    • 1970-01-01
    相关资源
    最近更新 更多