当我调用Generate()
时,不会触发与ObservableCollection(X
)关联的事件。
我做错了什么?
代码:
MyControl.xaml.cs
public ObservableCollection<double> X
{
get { return (ObservableCollection<double>)GetValue(XProperty); }
set { SetValue(XProperty, value); }
}
public static readonly DependencyProperty XProperty =
DependencyProperty.Register(
"X", typeof(ObservableCollection<double>),
typeof(MyControl),
new PropertyMetadata(
new ObservableCollection<double>(),
new PropertyChangedCallback(OnXChanged)));
private static void OnXChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var control = sender as MyControl;
// DoSomething
}
使用MyControl的XAML随机页面:
<local:MyControl
Title="Test"
X="{Binding TestX, Mode=TwoWay}"
/>
该页面的.cs
public sealed partial class MainPage : Page
{
public ObservableCollection<double> TestX { get; set; }
private static Random rand_ = new Random();
public MainPage()
{
this.InitializeComponent();
TestX = new ObservableCollection<double>();
}
private void Generate()
{
TestX.Clear();
for (int i = 0; i < 100; ++i)
{
TestX.Add(rand_.Next(1, 100));
}
}
....
}
请注意,我在输出窗口中看不到任何BindingExpression错误。
更新
我注意到如果在页面中这样做,它可以工作:
TestX = new ObservableCollection<double>();
this.MyUserControlInstance.X = TestX;