本文介绍了为什么不是这个数据绑定的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含点列表的视图模型类,我想将其绑定到一个折线。该折线拿起点的初步名单,但即使我实现INotifyPropertyChanged加附加分不另行通知。怎么了?
< StackPanel的>
<按钮单击=Button_Click>!加入< /按钮>
<折线X:名称=_行积分={结合积分}中风=黑StrokeThickness =5/>
< / StackPanel的>
C#端:
// code-背后
_line.DataContext =新视图模型();
私人无效Button_Click(对象发件人,RoutedEventArgs E)
{
//问题就在这里:什么都不会发生在屏幕上!
((视图模型)_line.DataContext).AddPoint();
}
// ViewModel类
公共类视图模型:INotifyPropertyChanged的
{
公共事件PropertyChangedEventHandler的PropertyChanged;
公共PointCollection积分{获得;组; }
公共视图模型()
{
PTS =新PointCollection();
Pts.Add(新点(1,1));
Pts.Add(新点(11,11));
}
公共无效AddPoint()
{
Pts.Add(新点(25,13));
如果(的PropertyChanged!= NULL)
的PropertyChanged(这一点,新PropertyChangedEventArgs(积分));
}
}
解决方案
更改PointCollections物业依赖属性:
公共PointCollection积分
{
{返回(PointCollection)的GetValue(PtsProperty); }
集合{的SetValue(PtsProperty,价值); }
}
//使用的DependencyProperty作为后备存储积分。这使得动画制作,造型,绑定等..
公共静态只读的DependencyProperty PtsProperty =
DependencyProperty.Register(积分的typeof(PointCollection)的typeof(视图模型),新UIPropertyMetadata(新PointCollection()));
顺便说一句这样做,你就不会需要触发PropertyChanged事件。
噢,对不起,你的对象需要自DependencyObject继承
公共类视图模型:DependencyObject的
{
// ...
}
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# side:
// 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"));
}
}
解决方案
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 Doing this, you won't need to fire the PropertyChanged event.
Oh sorry, and your object needs to inherit from DependencyObject
public class ViewModel : DependencyObject
{
//...
}
这篇关于为什么不是这个数据绑定的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!