简体   繁体   English

代码隐藏中的数据绑定拒绝工作

[英]Data Binding in code-behind refuses to work

I'm trying to set a data binding in code-behind but it doesn't want to work.我正在尝试在代码隐藏中设置数据绑定,但它不想工作。

When I do it in XAML like this:当我在 XAML 中这样做时:

<Label x:Name="lblSelectedItem" Margin="0,0,5,5" DockPanel.Dock="Left" Content="{Binding (Canvas.Left),ElementName=Ming}"></Label>

It works perfectly, but when I do it like this:它工作得很好,但是当我这样做时:

var X1Binding = new Binding("Canvas.Left") { ElementName="Ming"};
BindingOperations.SetBinding(lblSelectedItem, ContentProperty, X1Binding);

It doesn't get any value.它没有任何价值。

How do I do this properly?我该如何正确执行此操作?

Use parenthesis around Canvas.Left like this :像这样在Canvas.Left周围使用括号:

var X1Binding = new Binding("(Canvas.Left)") { ElementName = "Rect" };
BindingOperations.SetBinding(Lbl1, Label.ContentProperty, X1Binding);

You have to specify several Binding property values.您必须指定多个 Binding 属性值。

var X1Binding = new Binding("Canvas.Left") { ElementName="Ming"};
//X1Binding.Source = ViewModel; // Well the canvas is not on the view model so default value is the datacontext of the view.
X1Binding.Mode = BindingMode.TwoWay;
X1Binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
BindingOperations.SetBinding(lblSelectedItem, ContentProperty, X1Binding);

Try setting binding and propertypath like below:尝试设置绑定和属性路径,如下所示:

Binding binding = new Binding();
binding.ElementName = "Ming";
binding.Path = new PropertyPath(Canvas.LeftProperty);
lblSelectedItem.SetBinding(ContentControl.ContentProperty, binding);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM