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
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.