为什么这个数据绑定不起作用? [英] Why doesn't this data binding work?
本文介绍了为什么这个数据绑定不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个ViewModel类,它包含一个点列表,我试图将它绑定到一个Polyline。 Polyline接收点的初始列表,但是即使我实现了INotifyPropertyChanged,即使添加了附加点也没有注意到。怎么了?
I have a ViewModel class that contains a list of points, and I am trying to bind it to a Polyline. The Polyline picks up the initial list of points, but does not notice when additional points are added even though I implement INotifyPropertyChanged. What's wrong?
<StackPanel>
<Button Click="Button_Click">Add!</Button>
<Polyline x:Name="_line" Points="{Binding Pts}" Stroke="Black" StrokeThickness="5"/>
</StackPanel>
C#边:
// code-behind
_line.DataContext = new ViewModel();
private void Button_Click(object sender, RoutedEventArgs e)
{
// The problem is here: NOTHING HAPPENS ON-SCREEN!
((ViewModel)_line.DataContext).AddPoint();
}
// ViewModel class
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public PointCollection Pts { get; set; }
public ViewModel()
{
Pts = new PointCollection();
Pts.Add(new Point(1, 1));
Pts.Add(new Point(11, 11));
}
public void AddPoint()
{
Pts.Add(new Point(25, 13));
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("Pts"));
}
}
推荐答案
更改您的PointCollections属性为依赖属性:
Change your PointCollections Property to a dependency property:
public PointCollection Pts
{
get { return (PointCollection)GetValue(PtsProperty); }
set { SetValue(PtsProperty, value); }
}
// Using a DependencyProperty as the backing store for Pts. This enables animation, styling, binding, etc...
public static readonly DependencyProperty PtsProperty =
DependencyProperty.Register("Pts", typeof(PointCollection), typeof(ViewModel), new UIPropertyMetadata(new PointCollection()));
BTW执行此操作,您不需要触发PropertyChanged事件。
BTW Doing this, you won't need to fire the PropertyChanged event.
哦,对不起,你的对象需要继承自DependencyObject
Oh sorry, and your object needs to inherit from DependencyObject
public class ViewModel : DependencyObject
{
//...
}
这篇关于为什么这个数据绑定不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文