1

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

3
  • 1
    Is the template itself dynamic, or just the number of items and the data bound to them? If the latter, just create a new user control so that the template is static, and then dynamically create instances of that user control and bind data to that. That's at least...less bad. Commented Oct 8, 2013 at 17:22
  • only thing created in WPF is a TabControl. then the grid inside each tabitem and the stackpanel/labels are created dynamically on load as it reads data from SQL Commented Oct 8, 2013 at 17:28
  • still confused unfortunately bleh Commented Oct 8, 2013 at 17:28

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

what would i put for here: "GetYourCurrentViewModelWithSelectedGameProperty();"? that's the only thing i dont understand. ty!
@user1189352 You wanted to bind the data context to SelectedGame - you need to set the Source to the object that contains the SelectedGame property. That's typically your ViewModel layer, hence that naming.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.