我在设计我构建的自定义控件时遇到了一些问题。下面是控制源码:
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 property的属性值MyProperty无效。行:9位置: 30
我找不出导致这个错误的样式有什么问题。我还尝试将属性名称“完全限定”为"Local:AnotherControl.MyProperty“,但也不起作用。
发布于 2009-08-04 19:27:45
不能在样式中设置非依赖属性。
您需要将其定义为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); }
}https://stackoverflow.com/questions/1229388
复制相似问题