代码之家  ›  专栏  ›  技术社区  ›  Jonathan Allen

WPF:数据与代码绑定

  •  9
  • Jonathan Allen  · 技术社区  · 15 年前

    如何使用代码(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
    
    2 回复  |  直到 15 年前
        1
  •  14
  •   Matt Hamilton    15 年前

    是的,代码中的绑定与直接赋值有点不同(这就是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的)绑定到标签的内容属性。

        2
  •  5
  •   DanCH    15 年前

    您应该使用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);  
    

    希望能帮上忙