Page 1 of 1

How to create xaml dynamically based on controls

Posted: 29 Apr 2021, 14:03
by BartekW
Hey, how to create .xaml view based on current focused control?
If I have 4 buttons and I click one I want to show the content assigned to this button. I probably should use Content Presenter but how to bind it and where to define the content to each button?

Re: How to create xaml dynamically based on controls

Posted: 29 Apr 2021, 20:12
by KeldorKatarn

Re: How to create xaml dynamically based on controls

Posted: 29 Apr 2021, 20:40
by KeldorKatarn
If it needs to be based on some data or something this can also work:



ContentPresenter is not a control you want to use directly in a view. It is a placeholder for the controltemplate of a contentcontrol. It represents the place where that control
will put its content. So it's only for use inside a controltemplate.

ContentControl is what you're looking for as you can see in the examples.

Re: How to create xaml dynamically based on controls

Posted: 29 Apr 2021, 21:04
by BartekW
Thanks I rly appreciate becouse I rly wasted a lot of time! I hope it works also on UserControls right?

Re: How to create xaml dynamically based on controls

Posted: 29 Apr 2021, 21:08
by KeldorKatarn
Absolutely. In fact that's usually how you do nesting of controls and navigation in WPF applications. Usually you do some databinding and work with viewmodels however.
In fact I'm currently working on a framework for that.

But the idea is basically you have a viewmodel, which has a property of child content whch is another viewmodel.
Now you assign a datatemplate for each of your viewmodels like this:
<DataTemplate DataType="{x:Type ns:MyViewModelType}">
  <ns:MyUserControl />
</DataTemplate>
And then you bind the content of your contentcontrol, your 'host' area, to that property. Everytime the mainviewmodel switches to a new child viewmodel, the change is reflected in
the view, as the contentcontrol looks up a new datatemplate matching the new viewmodel.

That's a very widely used standard workflow in WPF applications to split the application into separate sub views that can be navigated in between.

Re: How to create xaml dynamically based on controls

Posted: 29 Apr 2021, 22:41
by BartekW
Yea I know the idea of ViewModel but it is usable for minicontent? I mean e.g grid 800x600 where current content should be showed?
And another thing. I have created user control and add to my view as <UserControls:MyControl/> and when noesis renders in .exe it doesnt show up :/ I have created even class and register it in main. But the constructor doesnt fire up, so GUI::LoadComponent cant fire up too. And Idk what to do.

Edit. Yea now my LoadComponent works, I had just bad .xaml name given, sorry :)