【问题标题】:WPF: Data binding with codeWPF:使用代码进行数据绑定
【发布时间】:2010-03-03 03:07:01
【问题描述】:

如何在代码(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

【问题讨论】:

    标签: wpf binding


    【解决方案1】:

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

    我可以给你一个 C# 的例子——不应该离 VB.NET 太远。

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

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

    【讨论】:

      【解决方案2】:

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

      希望能帮到你

      【讨论】:

        猜你喜欢
        • 2011-01-19
        • 2011-03-21
        • 2011-06-16
        • 2018-03-14
        • 1970-01-01
        • 1970-01-01
        • 2012-06-04
        • 2012-10-08
        相关资源
        最近更新 更多