简体   繁体   中英

How can I bind to the property of a class from the codebehind?

In my XAML I have this:

<TextBlock Text="{Binding Stats.Scores.Team}" Style="{StaticResource Column_Value_Large}" />

I need to be able to create that TextBlock, in it's entirety, in the codebehind. Here's what I have:

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);
}

However, the binding doesn't seem to be working. What's the appropriate way to set the binding in the codebehind?

Edit for context: my goal is to generate a bunch of these text boxes inside a big loop in the codebehind. See my revised example above which now shows the loop. Since I want to do it this way, I don't think there's any possible way for me to do it in the XAML; I would have to set the binding in the codebehind.

I think you use xaml in a wrong way. Why don t you set the TextBlock in the XAML code and bind its Visibility to a property or use a Style . Then you don . Then you don t have to create the binding in the codebehind. EDIT: Why don't you use a ItemPanel or something like that to which you bind your collection and give it a DataTemplate which displays the TextBoxes?

I got it.

My problem was using "Path" in SetBinding instead of "Source". The working code looks like this:

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);

}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM