【发布时间】:2017-05-19 20:07:22
【问题描述】:
代码使用Path 创建多边形。每次用户双击它都会关闭多边形并为第二个多边形添加另一个Path 对象,依此类推。我正在使用PointsToPathConverter 将Points 转换为Path 想要的集合。
积分被添加到Areas 集合中,但由于某种原因OnPropertyChanged("Areas"); 没有更新ItemsControl。可能是什么原因?
XAML
<ItemsControl ItemsSource="{Binding Areas}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Path Data="{Binding Path=., Converter={StaticResource ResourceKey=PointsToPathConverter}}" Stroke="Black" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
视图模型
public class VM : INotifyPropertyChanged
{
private ICommand _addPointCommand;
public ICommand AddPointCommand
{
get
{
if (_addPointCommand == null)
{
_addPointCommand = new RelayCommand<MouseButtonEventArgs>(AddPoint);
}
return _addPointCommand;
}
}
private ObservableCollection<List<Point>> _areas { get; set; }
public ObservableCollection<List<Point>> Areas
{
get
{
if (_areas == null)
{
_areas = new ObservableCollection<List<Point>>();
}
return _areas;
}
}
public VM()
{
Areas = new ObservableCollection<List<Point>>();
Areas.Add(new List<Point>());
}
private void AddPoint(MouseButtonEventArgs e)
{
var curPoints = Areas[Areas.Count - 1];
curPoints.Add(e.GetPosition((IInputElement)e.Source));
if (e.ClickCount == 2 && curMaskPoints.Count > 0)
{
curMaskPoints.Add(curMaskPoints[0]);
Areas.Add(new List<Point>());
}
OnPropertyChanged("Areas");
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
public class PointsToPathConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var points = (value as List<Point>);
if (points.Count > 0)
{
Point start = points[0];
List<LineSegment> segments = new List<LineSegment>();
for (int i = 1; i < points.Count; i++)
{
segments.Add(new LineSegment(points[i], true));
}
PathFigure figure = new PathFigure(start, segments, false); //true if closed
PathGeometry geometry = new PathGeometry();
geometry.Figures.Add(figure);
return geometry;
}
else
{
return null;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
#endregion
}
b
【问题讨论】:
-
您可能想在 Areas 属性发生变化时通知您,但这里 Areas 的值永远不会改变。 Areas 的值是对 ObservableCollection 实例的引用。
-
PropertyChanged 事件只会通知。不多不少。绑定控件决定如何处理该通知,有些控件会将旧值与新值进行比较,如果没有变化,它们将什么也不做。
-
@EdPlunkett,然后当用户单击时,它会向集合
var curPoints = Areas[Areas.Count - 1]; curPoints.Add(e.GetPosition((IInputElement)e.Source));添加一个点。然后我引发属性事件更改为刷新整个ItemsControl。 -
你需要类似 ObservableCollection
> -
对不起,我们不能。我们可以用 ObservableCollection
> ... 来做到这一点,但你也可以。只需将 List 更改为 ObservableCollection
标签: c# wpf data-binding observablecollection