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

时间:2016-04-04 03:55:57

标签: c# wpf

我试图在代码隐藏中设置数据绑定,但它并不想工作。

当我在XAML中这样做时:

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

它完美无缺,但当我这样做时:

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

它没有任何价值。

我该如何正确地做到这一点?

3 个答案:

答案 0 :(得分:1)

Canvas.Left周围使用括号,如下所示:

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

答案 1 :(得分:0)

您必须指定几个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);

答案 2 :(得分:0)

尝试设置绑定和属性路径,如下所示:

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