Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: Data binding with code

Tags:

binding

wpf

How do I use data-binding from code (C# or VB)?

This is what I have so far, but it is displaying Binding.ToString instead of 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
like image 511
Jonathan Allen Avatar asked Mar 03 '10 03:03

Jonathan Allen


2 Answers

You should use m_Rep as a Source of Binding

I have some sample C# code for you as below

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);  

Hope to help

like image 154
DanCH Avatar answered Sep 28 '22 07:09

DanCH


Yes, binding in code is a little different from straight assignment (which is how XAML makes it look like it works).

I can give you an example in C# - shouldn't be too far removed from VB.NET.

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

So the "SetBinding" method binds the "FirstName" path (of the DataContext) to the label's Content property.

like image 28
Matt Hamilton Avatar answered Sep 28 '22 06:09

Matt Hamilton