2010-03-03 60 views
8

如何使用代码(C#或VB)的数据绑定?WPF:与代码的数据绑定

这是我到目前为止,但它显示Binding.ToString而不是m_Rep.FirstName

Public ReadOnly Property TabCaption As Object 
    Get 
     Return New Label With {.Foreground = Brushes.Black, .Content = New Binding("FirstName"), .DataContext = m_Rep} 
    End Get 
End Property 

回答

13

是的,绑定在代码中与直接赋值有点不同(这是XAML使它看起来像它的工作原理)。

我可以给你一个在C#中的例子 - 不应该太离开VB.NET。

var label = new Label { Foreground = Brushes.Black, DataContext = m_Rep }; 
label.SetBinding(Label.ContentProperty, new Binding("FirstName")); 
return label; 

因此,“SetBinding”方法将“FirstName”路径(DataContext的)绑定到标签的Content属性。

5

你应该使用M_REP作为绑定

的来源我对你有一些C#示例代码如下

Person myDataSource = new Person("Joe"); 
// Name is a property which you want to bind 
Binding myBinding = new Binding("Name"); 
myBinding.Source = myDataSource; 
// myText is an instance of TextBlock 
myText.SetBinding(TextBlock.TextProperty, myBinding); 

希望能帮到