我创建了一个简单的评级用户控件,当我使用绑定时,这个控件在WinRT工作时不会出现问题,它在windows手机上运行正常,这是我的控件:
public sealed partial class RatingControl : UserControl
{
public int Rate { get { return (int)GetValue(RateProperty); } set { SetValue(RateProperty, value); } }
public static readonly DependencyProperty RateProperty = DependencyProperty.Register("Rate",
typeof(int),
typeof(RatingControl), null);
public RatingControl()
{
this.InitializeComponent();
this.Loaded += RatingControl_Loaded;
}
void RatingControl_Loaded(object sender, RoutedEventArgs e)
{
List<Image> Images = new List<Image>();
for (int i = 0; i < 5; i++)
{
Image img = new Image { Width = 35, Height = 35, Margin = new Thickness(3) };
img.Source = new BitmapImage { UriSource = new System.Uri("ms-appx:Images/Stars/notFilled.png") };
Images.Add(img);
sp.Children.Add(img);
}
for (int i = 0; i < Rate; i++)
Images[i].Source = new BitmapImage { UriSource = new System.Uri("ms-appx:Images/Stars/Filled.png") };
}
}
当我对该值进行硬编码时,它可以正常工作:
<local:RatingControl Rate="3" />
但是当我使用Binding时,它只显示零星。我检查了Rate的值,它始终为零。
<local:RatingControl Rate="{Binding Decor, Mode=TwoWay}" />
更新:我刚刚发现绑定发生在我得到Rate的值之前,所以它始终为零。我该如何解决这个问题?我需要绑定才能获得值。此外,我认为每次更改Rate值时都会发生绑定。
解决方案:我没有正确实现DependencyObject,我应该这样做:
public static readonly DependencyProperty RateProperty = DependencyProperty.Register("Rate",
typeof(int),
typeof(RatingControl), new PropertyMetadata(0, new PropertyChangedCallback(BindRateControl)));
答案 0 :(得分:2)
解决方案:我没有正确实现DependencyObject,我应该这样做(添加一个回调方法):
public static readonly DependencyProperty RateProperty = DependencyProperty.Register("Rate",
typeof(int),
typeof(RatingControl),
new PropertyMetadata(0, new PropertyChangedCallback(BindRateControl)));
答案 1 :(得分:0)
您是否尝试从代码隐藏中添加UserControl。这有助于确保在获取值后触发UserControl。