2014-08-31 96 views
1

我试图在样式中设置附加属性,我想用它们来附加行为。但我无法得到它的工作。 赫雷什代码:在样式设置器中设置自定义附加属性

附加属性

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> 

+0

你有没有用括号尝试的所有者类型'(测试:TestBehaviour.Test)'? – Pragmateek 2014-08-31 19:03:15

+1

@Pragmateek刚刚尝试过。不会编译((测试未声明的命名空间)也试过“(TestBehaviout.Test)” – 2014-08-31 19:14:43

回答

3

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

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

RegisterAttached MSDN文档:

ownerType - 即注册依赖属性

+0

很酷的工作。非常感谢 – 2014-08-31 19:28:53

相关问题