Chris
Chris

Reputation: 27384

Bind to XAML in code

If I have a resource loader that creates XAML on the fly (in this case a StackPanel is returned) how can I bind to this in the xaml?

My property is:

public StackPanel InfoPane {get;set;}

I have tried this but it doesnt work

<Grid>
    <ContentPresenter Content="{Binding InfoPane}" />
</Grid>

Upvotes: 1

Views: 85

Answers (2)

Heinzi
Heinzi

Reputation: 172260

(Sorry, too long for a comment.)

You approach is correct, the following minimal example works for me:

XAML:

<Grid>
    <ContentPresenter Content="{Binding InfoPane}" />
</Grid>

Codebehind:

public StackPanel InfoPane { get; set; }

public MainWindow()
{
    InitializeComponent();
    InfoPane = new StackPanel();
    InfoPane.Children.Add(new TextBlock { Text = "dynamically created" });
    this.DataContext = this;
}

So, your problem must lie somewhere else. Maybe you set your InfoPane after setting the DataContext property of your window? Note that you do not invoke PropertyChanged, so the UI has no way of knowing that InfoPane has changed.

Upvotes: 1

Emond
Emond

Reputation: 50672

You do not need binding, all you need to do is add the StackPanel to the Children collection when the StackPanel has been created.

That said, my advise is to take a different route:

Put a content control in the Grid and bind its Content to actual content (not a control) and register for each type of content a ContentTemplate so the ContentControl will select the correct template depending on the content being displayed.

Creating UI in code should be avoided as much as possible because it is hard to maintain and WPF has ways to handle content dependent UI.

Upvotes: 1

Related Questions