2014-08-31 149 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