Windows phone 7 silverlight用户控制:数据绑定不能在自定义属性上工作



我有一个相当简单的用户控件(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的"set"代码从未被调用,我也没有在调试输出窗口中看到数据绑定错误。请注意,下面我试图将相同的值分配给一个标准属性(Width),在这种情况下,值被正确地传递给它。

<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()方法。

因此,值规范化的适当位置应该是依赖属性的属性更改回调:

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

最新更新