2009-08-04 100 views
3

我在構建自定義控件時遇到了一些麻煩。這裏的控制源:XamlParseException - 屬性的屬性值(...)無效屬性

namespace SilverlightStyleTest 
{ 
    public class AnotherControl: TextBox 
    { 
     public string MyProperty { get; set; } 
    } 
} 

在同一個命名空間&項目,我嘗試創建一個風格,像這樣的myProperty的二傳手:

<UserControl x:Class="SilverlightStyleTest.MainPage" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:Local="clr-namespace:SilverlightStyleTest"> 

    <UserControl.Resources> 
     <Style x:Name="AnotherStyle" TargetType="Local:AnotherControl"> 
      <Setter Property="Width" Value="200"/> 
      <Setter Property="MyProperty" Value="Hello."/> 
     </Style> 
    </UserControl.Resources> 

    <Grid x:Name="LayoutRoot"> 
     <Local:AnotherControl Style="{StaticResource AnotherStyle}"/> 
    </Grid> 
</UserControl> 

我結束了在運行時錯誤: 無效的屬性爲屬性Property指定值MyProperty。 [行:9位置:30]

我無法弄清楚導致此錯誤的風格有什麼問題。我也嘗試過「完全限定」這個屬性名稱爲「Local:AnotherControl.MyProperty」,但這也沒有奏效。

+0

你的類名爲`AnotherTextBox`,但你的XAML引用`AnotherControl`。那麼是哪一個呢?請相應地更正問題。 – 2009-08-04 19:23:45

+0

我假設它在隱藏名稱時出現錯字,但在底部示例中使用了「AnotherControl」,而不是頂部的「AnotherTextbox」。 – 2009-08-04 19:23:57

回答

4

非依賴項屬性不能設置爲樣式

你需要將它定義爲一個DependencyProperty:

public static readonly DependencyProperty MyPropertyProperty = 
    DependencyProperty.Register("MyProperty", typeof(string), typeof(AnotherTextBox), 
     new FrameworkPropertyMetadata((string)null)); 

public string MyProperty 
{ 
    get { return (string)GetValue(MyPropertyProperty); } 
    set { SetValue(MyPropertyProperty, value); } 
}