windows phone 7 silverlight用户控件:自定义属性上的数据绑定不起作用

windows phone 7 silverlight用户控件:自定义属性上的数据绑定不起作用,silverlight,data-binding,windows-phone-7,Silverlight,Data Binding,Windows Phone 7,我有一个相当简单的用户控件(RatingControl),它的依赖属性定义如下: public partial class RatingControl : UserControl { public RatingControl() { InitializeComponent(); } public static readonly DependencyProperty RatingValueProperty = DependencyPrope

我有一个相当简单的用户控件(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); }
    }

如果我直接分配,此控件将正确接收额定值:

<gtcontrols:RatingControl RatingValue="2.0" />

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

<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(甚至未调用方法集)

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

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

因此,值规范化的正确位置应该是dependency属性的property changed回调:

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;  
}