user1189352
user1189352

Reputation: 3885

How to Databind through C# and not WPF?

So i'm using WPF the wrong way and i have a bunch of dynamically created objects on load... i'm trying to figure out how to databind through C#... what would be the equivalent C# code to this:

<StackPanel DataContext="{Binding SelectedGame}">
    <Label Content="{Binding HomeScoreText}" />
    <Label Content="{Binding AwayScoreText}" />
</StackPanel>

i'm having trouble finding examples of this online.. thanks

Upvotes: 1

Views: 80

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564433

MSDN has a sample page demonstrating how to Create a Binding In Code.

In your case, you could do the above via:

StackPanel panel = new StackPanel();
Label label1 = new Label();
Label label2 = new Label();

panel.Children.Add(label1);
panel.Children.Add(label2);

var yourVM = GetYourCurrentViewModelWithSelectedGameProperty();

// Set data context
Binding binding = new Binding("SelectedGame");
binding.Source = yourVM;
panel.SetBinding(FrameworkElement.DataContextProperty, binding);

binding = new Binding("HomeScoreText");
binding.Source = panel.DataContext;
label1.SetBinding(ContentControl.ContentProperty, binding);

binding = new Binding("AwayScoreText");
binding.Source = panel.DataContext;
label2.SetBinding(ContentControl.ContentProperty, binding);

Upvotes: 2

Related Questions