【发布时间】:2014-12-22 07:31:05
【问题描述】:
我有一个UserControl,其依赖属性名为ItemWidth。我将通过Style 将UserControl 中的几个路径的宽度绑定到此依赖项属性,但在设计时我得到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 中的每个路径定义宽度属性。
【问题讨论】:
标签: c# silverlight binding user-controls dependency-properties