Set custom attached property in style setter

Deadly 提交于 2019-11-28 11:56:18

问题


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:

Attached property

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>


回答1:


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

See the MSDN documentation for RegisterAttached:

ownerType - The owner type that is registering the dependency property



来源:https://stackoverflow.com/questions/25595272/set-custom-attached-property-in-style-setter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!