将 WPF Canvas 子项绑定到 ObservableCollection
在我的 WPF 应用程序中,我有一个 Canvas,可以在其中进行一些绘图。早些时候,我在后面的代码中处理了绘图,但现在我已将所有内容分解到 ViewModel 中。这给我带来了一些挑战。
我有一些 InkPresenter 对象保存笔划。早些时候,我将它们作为子项添加到后面代码中的 Canvas 中 - 就像这样:
// Build an InkPresenter:
var someInkPresenter = BuildInkPresenter(..);
//_myCanvas is the <Canvas> I want to display it in:
_myCanvas.Children.Add(someInkPresenter);
现在 - 不在保存 _myCanvas 的 XAML 代码后面构建 InkPresenter 我需要以不同的方式执行此操作。我想做的是创建一个 InkPresenter 并将其添加到集合中:
public ObservableCollection<InkPresenter> Drawings;
我现在的问题是如何将 Canvas 绑定到此 ObservableCollection - 并在添加到集合时显示 InkPresenter。我可以使用数据绑定以某种方式实现这一点吗?
In my WPF application I have a Canvas in which I do some drawing. Earlier I handled the drawing in the code behind, but now I've factored everything out to a ViewModel. This gives me some challenges..
I have a few InkPresenter objects holding Strokes. Earier I added them as children to the Canvas in the code behind - like this:
// Build an InkPresenter:
var someInkPresenter = BuildInkPresenter(..);
//_myCanvas is the <Canvas> I want to display it in:
_myCanvas.Children.Add(someInkPresenter);
Now - not building the InkPresenter in the code-behind of the XAML that holds _myCanvas I need to do this differently. What I'd like to do is to create an InkPresenter and add it to a collection:
public ObservableCollection<InkPresenter> Drawings;
My problem now is how to bind the Canvas to this ObservableCollection - and have the InkPresenters displayed when added to the collection. Can I achieve this using Data Bindings somehow?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为你可以使用 ItemsControl 来完成此操作+ ItemsPanelTemplate。像这样:
要了解有关此方法的更多信息,请参阅 Dr.WPF:ItemsControl:A to Z (P 代表面板< /a>)
I think you can do this with ItemsControl + ItemsPanelTemplate. Like this:
To read more about this approach refer to Dr.WPF: ItemsControl: A to Z (P is for Panel)
Anvaka 建议的解决方案很棒,但正如 John Bowen 指出的那样,如果您想将项目实际绑定到 Canvas 附加属性,您需要了解更多信息。
以下是如何绑定到 Canvas.Left 和 Canvas.Top 的示例:
顺便说一句,我在 这个问题,在我尝试了 Anvaka 的建议后,绑定不起作用。
希望这对其他人有帮助,寻找相同的答案。
The solution Anvaka suggested is great, but as John Bowen pointed out you need to know a bit more, if you would like to actually bind your items to the Canvas attached properties.
Here's an example on how to bind to Canvas.Left and Canvas.Top:
Btw, I found the solution on this question, after I tried Anvaka's suggestion, where the binding didn't work.
Hopefully this helps others, looking for the same answer.