【问题标题】:Silverlight Binding to UserControl's DependencyProperty throws NullReferenceExceptionSilverlight 绑定到 UserControl 的 DependencyProperty 引发 NullReferenceException
【发布时间】:2014-12-22 07:31:05
【问题描述】:

我有一个UserControl,其依赖属性名为ItemWidth。我将通过StyleUserControl 中的几个路径的宽度绑定到此依赖项属性,但在设计时我得到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


    【解决方案1】:

    我认为问题在于 PropertyMetadata 初始化,它将 21 转换为整数。

    如果你使用

    new PropertyMetadata(21d) 
    

    new PropertyMetadata(21.00)
    

    不会抛出空异常。

    【讨论】:

    • 使用double作为dependencyproperty并用它来绑定Width&Height属性是不是真的?
    猜你喜欢
    • 2012-06-06
    • 2013-06-03
    • 1970-01-01
    • 2011-07-16
    • 1970-01-01
    • 2013-01-20
    • 2014-06-22
    • 2016-05-13
    相关资源
    最近更新 更多