我创建了一个silverlight用户控件(继承自UserControl,包含xaml和xaml.cs两个文件):
public partial class SilverlightControl1 : UserControl { public int MinimumPrefixLength { get { return (int)GetValue(MinimumPrefixLengthProperty); } set { SetValue(MinimumPrefixLengthProperty, value); } } public static readonly DependencyProperty MinimumPrefixLengthProperty = DependencyProperty.Register( "MinimumPrefixLength", typeof(int), typeof(SilverlightControl1), new PropertyMetadata(1, OnMinimumPrefixLengthPropertyChanged)); private static void OnMinimumPrefixLengthPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { }
//其余代码略
}
然后我又自定义了一个控件(继承自Control,只包含cs文件,不包含xaml文件):
public class AutoCompleteBox : Control { public int MinimumPrefixLength { get { return (int)GetValue(MinimumPrefixLengthProperty); } set { SetValue(MinimumPrefixLengthProperty, value); } } public static readonly DependencyProperty MinimumPrefixLengthProperty = DependencyProperty.Register( "MinimumPrefixLength", typeof(int), typeof(AutoCompleteBox), new PropertyMetadata(1, OnMinimumPrefixLengthPropertyChanged)); private static void OnMinimumPrefixLengthPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { } }
定义好了后,我在另一个xaml页面中使用两个控件:
<SilverlightApplication1:SilverlightControl1 x:Name="uc" MinimumPrefixLength="{Binding Value4}"/> <SilverlightApplication1:AutoCompleteBox x:Name="a2" MinimumPrefixLength="{Binding Value4}"/>
其中Value4是实现了INotifyPropertyChanged接口的属性,然后我写了一下测试代码:
Value4 = DateTime.Now.Millisecond; MessageBox.Show( a2.MinimumPrefixLength.ToString() + " - " + uc.MinimumPrefixLength.ToString() );
惊奇的发现,当更改Value4的时候,只有a2的MinimumPrefixLength发生变化,uc的MinimumPrefixLength始终是默认值,何故????
也就是说,继承UserControl的控件的自定义依赖属性,不支持数据绑定,而继承自Control的控件却支持绑定,怎么搞的?
我也遇到了这个问题,一模一样,有人说可能是DataContext的问题,不知道。帮顶