![](/img/trans.png)
[英]Binding to a usercontrol's DependencyProperty is not calling the setter
[英]Silverlight Binding to UserControl's DependencyProperty throws NullReferenceException
我有一个UserControl
带有一个名为ItemWidth
的依赖项属性。 我将通过Style
将UserControl
中几个Path的宽度绑定到此依赖项属性,但是在设计时我得到了NullReferenceException。 这是代码:
MyUserControl.xaml.cs
public partial class MyUserControl: UserControl
{
public MyUserControl()
{
InitializeComponent();
}
public double ItemWidth
{
get { return (double )GetValue(ItemWidthProperty);}
set { SetValue(ItemWidthProperty, value);}
}
public static readonly DependencyProperty ItemWidthProperty =
DependencyProperty.Register("ItemWidth", typeof(double),
typeof(MyUserControl), new PropertyMetadata(21));
MyUserControl.xaml
<UserControl x:Name = "root" ....>
<StackPanel DataContext="{Binding ElementName=root}"
Orientation="Horizontal">
<StackPanel.Resources>
<Style TargetType="Path">
<Setter Property="Width" Value="{Binding ItemWidth}"/>
</Style>
</StackPanel.Resources>
<Path Data="some path"/>
<Path Data="some path"/>
<Path Data="some path"/>
<Path Data="some path"/>
<Path Data="some path"/>
</StackPanel>
</UserControl>
如果我分别为每个路径设置宽度,则不会发生错误。 但是我想使用样式,并且不为UserControl
每个Path定义width属性。
我认为问题在于PropertyMetadata初始化,它将21强制转换为整数。
如果您使用
new PropertyMetadata(21d)
要么
new PropertyMetadata(21.00)
它不会抛出null异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.