WPF:使用代码进行数据绑定

Jon*_*len 9 wpf binding

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

这是我到目前为止,但它显示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
Run Code Online (Sandbox Code Playgroud)

Mat*_*ton 14

是的,代码中的绑定与直接赋值略有不同(这就是XAML使它看起来像它的工作方式).

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

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

因此,"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);  
Run Code Online (Sandbox Code Playgroud)

希望能有所帮助