[英]How can I bind to the property of a class from the codebehind?
在我的XAML中,我有以下内容:
<TextBlock Text="{Binding Stats.Scores.Team}" Style="{StaticResource Column_Value_Large}" />
我需要能够在背后的代码中完整创建该TextBlock。 这是我所拥有的:
foreach (var Stats in player){
var columnHeaderScore = new TextBlock
{
Style = Application.Current.Resources["Column_Value_Large"] as Style,
};
columnHeaderScore.SetBinding(TextBlock.TextProperty, new Binding
{
Path = new PropertyPath("Stats.Scores.Team"),
});
columnHeaderStackPanel.Children.Add(columnHeaderScore);
}
但是,绑定似乎不起作用。 在后台代码中设置绑定的合适方法是什么?
编辑上下文:我的目标是在背后的代码大循环内生成一堆这样的文本框。 请参阅我上面修改过的示例,该示例现在显示了循环。 由于我想这样做,所以我认为XAML中没有任何可行的方法。 我将不得不在后面的代码中设置绑定。
我认为您以错误的方式使用xaml。 为什么不在in the XAML code and bind its
t you set the
TextBlock in the XAML code and bind its
可见性in the XAML code and bind its
to a property or use a
样式. Then you don
. Then you don
不必在背后的代码中创建绑定。 编辑:为什么不使用ItemPanel或类似的东西将绑定集合并赋予它一个显示TextBoxes的DataTemplate?
我知道了。
我的问题是在SetBinding中使用“ Path”而不是“ Source”。 工作代码如下所示:
foreach (var Stats in player){
var columnHeaderScore = new TextBlock
{
Style = Application.Current.Resources["Column_Value_Large"] as Style,
};
columnHeaderScore.SetBinding(TextBlock.TextProperty, new Binding
{
Source = Stats.Scores.Team,
});
columnHeaderStackPanel.Children.Add(columnHeaderScore);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.