一个用户控件的位置和大小绑定在WPF中的画布内 [英] Binding the position and size of a UserControl inside a Canvas in WPF

查看:710
本文介绍了一个用户控件的位置和大小绑定在WPF中的画布内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们需要动态创建(即在运行时,通过code-后面)用户控件和它们放在画布的位置。 我们希望这些相当大的和可拖动用户控件的位置(Canvas.Left和Canvas.Top)和宽度绑定到的ObservableCollection&所述(!)(!);>。当用户拖动或调整大小的控件measn,数据源就会自动更新。

We need to dynamically create (i.e. during runtime, via code-behind) UserControls and position them on a Canvas. We want to bind the position (Canvas.Left and Canvas.Top) and width of those sizable (!) and draggable (!) UserControls to a ObservableCollection<>. That measn when the user drags or resizes the control, the datasource gets automatically updated.

我们怎么能做到这一点,如果用户控件包含在其中又用一个列表框,我们要绑定到的DataContext设置的收集一个DataTemplate?

How would we achieve this if the Usercontrol is contained in a DataTemplate which in turn is used by a ListBox whose DataContext is set to the collection we want to bind to?

在换句话说,我们如何绑定控件的位置,并且没有在XAML中存在的规模,但只有(因为它是通过点击和拖动鼠标创建)code?

In other words, how do we bind a control's position and size that doesn't exist in XAML, but in code only (because it's created by clicking and dragging the mouse)?

注意,集合可以是空的或不是空的,也就是说,存储在数据源的大小和位置必须被正确地绑定到以便该用户控件的尺寸和正确定位在帆布 - 通过数据绑定。 这可能吗?

Notice that the collection can be empty or not empty, meaning that the size and position stored in datasource must be correctly bound to so that the UserControl can be sized and positioned correctly in the Canvas - via DataBinding. Is this possible?

推荐答案

您是否尝试过使用模式=双向绑定?

Have you tried using a Mode=TwoWay binding?

<YourUserControl 
    Canvas.Top="{Binding TopProperty, Mode=TwoWay}" 
    Canvas.Left={Binding LeftProperty, Mode=TwoWay}" 
    Height="{Binding HeightProperty, Mode=TwoWay}" 
    Width="{Binding WidthProperty, Mode=TwoWay}" />

我不相信双向绑定将调整大小或拖动​​工作拖放操作,但是,只有一个办法,找出。

I'm not convinced two-way binding will work with resize or drag and drop operations, but there's only one way to find out.

这篇关于一个用户控件的位置和大小绑定在WPF中的画布内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆