2009-08-04 97 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); } 
}