【问题标题】:windows phone 7 silverlight user control: data binding not working on custom propertywindows phone 7 silverlight 用户控件:数据绑定不适用于自定义属性
【发布时间】:2011-07-24 18:10:15
【问题描述】:

我有一个相当简单的用户控件 (RatingControl),它的依赖属性定义如下:

    public partial class RatingControl : UserControl
{
    public RatingControl()
    {
        InitializeComponent();
    }

    public static readonly DependencyProperty RatingValueProperty = DependencyProperty.Register("RatingValue", typeof(double), typeof(RatingControl), new PropertyMetadata(0.0));

    public double RatingValue
    {
        set 
        { 
            double normalizeValue = 0.0;

            if (value > 10.0)
            {
                normalizeValue = 10.0;
            }
            else if (value > 0.0)
            {
                normalizeValue = value;
            }

            SetValue(RatingValueProperty, normalizeValue);
            RenderRatingValue();
        }
        get { return (double)GetValue(RatingValueProperty); }
    }

...

如果我直接分配,此控件会正确接收 RatingValue:

<gtcontrols:RatingControl RatingValue="2.0" />

但是,如果我尝试使用数据绑定来分配它,它就不起作用。永远不会调用 RatingValue 的“设置”代码,我也不会在调试输出窗口中看到数据绑定错误。 请注意下面我尝试将相同的值分配给标准属性(宽度),在这种情况下,该值被正确传递给它。

<StackPanel>
                <TextBox Name="Test" Text="200.0" />

                <gtcontrols:RatingControl Width="{Binding ElementName=Test, Path=Text}" RatingValue="{Binding ElementName=Test, Path=Text}" />
                <TextBlock Text="{Binding ElementName=Test, Path=Text}" />
            </StackPanel>

不仅 TextBlock 正确接收值。 RatingControl 也接收到宽度,正确设置为 200 像素;但是,RatingValue 没有设置(甚至没有调用方法集)

我错过了什么? 提前致谢。

【问题讨论】:

    标签: silverlight data-binding windows-phone-7


    【解决方案1】:

    问题是绑定系统不使用 CLR 属性包装器(getter 和 setter)来分配依赖属性的值。这些只是为了方便起见,因此您可以像使用代码中的普通属性一样使用该属性。它在内部使用 SetValue()/GetValue() 方法。

    因此,值规范化的正确位置是依赖属性的属性更改回调:

    public static readonly DependencyProperty RatingValueProperty =
        DependencyProperty.Register("RatingValue", typeof(double), typeof(RatingControl), 
        new PropertyMetadata(0.0, new PropertyChangedCallback(RatingValuePropertyChanged))));
    
    static void RatingValuePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        var ratingControl = (RatingControl)sender;
        var val = (double)e.NewValue;
    
        double normalizeValue = 0.0;
    
        if (val > 10.0)
        {
            normalizeValue = 10.0;
        }
        else if (val > 0.0)
        {
            normalizeValue = val;
        }      
    
        ratingControl.RatingValue = normalizeValue;  
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-18
      • 1970-01-01
      • 2014-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-25
      • 1970-01-01
      相关资源
      最近更新 更多