wpf - 在样式 setter 中设置自定义附加属性

标签 wpf styles attached-properties

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

附加属性

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 - The owner type that is registering the dependency property

关于wpf - 在样式 setter 中设置自定义附加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25595272/

相关文章:

wpf - 如何使用 FsXaml 的 CommandDependecy/(ies)

css - 没有功能的列表样式图像

c# - 使用 Setter 更新样式触发器中的自定义附加属性

c# - 将属性附加到用户控件并在设计时更新它

c# - WPF Datagrid 单元格、cellinfo 和 selectedcells + 自定义选择

c# - 在 ShowDialog() 方法中寻找 NullReferenceException 的来源

wpf - 自定义样式列表框 - 如何保留所选项目的样式?

类层次结构中的 Java 可选接口(interface)

wpf - 无法获得附加的属性(property)值(value)

WPF 工具提示 ControlTemplate 不显示内容