1

因此,我以错误的方式使用 WPF,并且加载了一堆动态创建的对象...我试图弄清楚如何通过 C# 进行数据绑定...与此等效的 C# 代码是什么:

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

我在网上找不到这样的例子..谢谢

4

1 回答 1

2

MSDN 有一个示例页面,演示如何在代码中创建绑定

在您的情况下,您可以通过以下方式执行上述操作:

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);
于 2013-10-08T17:26:21.453 回答