Width 属性的 WPF 数据绑定
我试图将 Canvas 的 Width 属性绑定到 Shape 实例的 Width 属性。因此,当 Canvas 宽度获取新值时,应该更新 Shape 宽度
,我想在代码中执行此操作,而不使用 XAML,因为我在运行时创建这些元素。
我尝试了这个,但没有成功(代码位于我的画布内):
Binding binding = new Binding();
binding.Mode = BindingMode.OneTime;
binding.Source = this;
binding.Path = new PropertyPath("Width");
shape.SetBinding(FrameworkElement.WidthProperty, binding);
非常感谢您的帮助!
克斯曼
I'm trying to bind the Width property of a Canvas to the Width property of a Shape instance. So the Shape Width should be updated when the Canvas Width gets a new value
I want to do that in code, without XAML, because I create these elements on runtime.
I tried this, but it didnt work (the code is inside of my Canvas):
Binding binding = new Binding();
binding.Mode = BindingMode.OneTime;
binding.Source = this;
binding.Path = new PropertyPath("Width");
shape.SetBinding(FrameworkElement.WidthProperty, binding);
Thanks a lot for your help!
ksman
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
OneTime
看起来不对。我认为您想使用OneWay
或TwoWay
。检查BindingModes编辑
由于
OneWay
和ActualWidth
没有解决您的问题,我建议您使用调试绑定的工具。我使用 Snoop 因为它是免费的,但还有其他的。如果没有这样的工具来调试 WPF 可能会很痛苦。OneTime
looks wrong. I think you want to useOneWay
orTwoWay
. Check the BindingModesEdit
Since
OneWay
andActualWidth
didn't fix your problem, I should recommend you use a tool for debugging bindings. I use Snoop because it is free, but there are others. Debugging WPF without a tool like this can be painful.您可能想要绑定到
ActualWidth
而不是Width
。宽度
是布局过程中的输入 - 您可以(但不必)指定它。ActualWidth
是布局过程的输出 - 它是您在屏幕上看到的实际宽度。这部分取决于Width
(如果存在),但也有其他因素影响(特别是如果您没有在 XAML 中显式设置Width
)。You probably want to bind to
ActualWidth
and notWidth
.Width
is an input into the layout process -- it's something you may (but don't have to) specify.ActualWidth
is an output of the layout process -- it's the actual width that you see on the screen. This is partly determined byWidth
, if present, but other factors go into it too (especially if you didn't explicitly setWidth
in your XAML).