我一直在试图弄清楚如何绑定ObservableCollection<FrameworkElements>
到 ItemsControl。我有一个现有的项目,它严重依赖于代码隐藏和画布,没有绑定,我正在尝试更新它以使用 mvvm 和 prism。
ObservableCollection 将填充许多 Path 项。它们是从我使用的外部库生成的。当我手动操作画布本身时,库可以正常运行。
以下是 ViewModel 中的代码片段:
ObservableCollection<FrameworkElement> _items;
ObservableCollection<FrameworkElement> Items
{
get { return _items; }
set
{
_items = value;
this.NotifyPropertyChanged("Items");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
支持XAML
<ItemsControl ItemsSource="{Binding Items}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas x:Name="canvas" IsItemsHost="True">
<Canvas.Background>
<SolidColorBrush Color="White" Opacity="100"/>
</Canvas.Background>
</Canvas>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Path/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
我遇到的问题是路径永远不会绘制。关于我哪里出错以及从哪里开始调试过程有什么建议吗?
您的视图模型应该包含路径的抽象表示,例如
public class PathData
{
public Geometry Geometry { get; set; }
public Brush Fill { get; set; }
public Brush Stroke { get; set; }
public double StrokeThickness { get; set; }
// ... probably more Stroke-related properties
}
如果您现在有 PathData 对象的集合,例如
public ObservableCollection<PathData> Paths { get; set; }
您的 ItemsControl 可能有一个 ItemsTemplate,如下所示:
<ItemsControl ItemsSource="{Binding Paths}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Path Data="{Binding Geometry}" Fill="{Binding Fill}"
Stroke="{Binding Stroke}" StrokeThickness="{Binding StrokeThickness}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
您现在可以像这样添加 PathData 实例:
Paths.Add(new PathData
{
Geometry = new RectangleGeometry(new Rect(100, 100, 100, 100)),
Fill = Brushes.AliceBlue,
Stroke = Brushes.Red,
StrokeThickness = 2
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)