Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF : dynamic view/content

Tags:

wpf

I'm a bit beginner in WPF, so I ask this..

Let's say I have a window, and inside the window I want to have something like container, could be just border or maybe panel (in winform terms). The content of container is binded to the selected option (e.g:button). So, for instance, when user selects OPTION 1, the container shows chart; when user selects OPTION 2, the container shows listview filled with data; when user selects OPTION 3, the container shows another things, and so on.

What is the best/nicest (or easiest maybe) approach to do this? I'm thinking about using user control for the content of the container, but don't know if this is nice solution neither the performance for using user control to show little bit complex things and maybe some calculations. Any other idea guys?

illustration:

like image 881
bagz_man Avatar asked Oct 15 '25 07:10

bagz_man


1 Answers

I solved this with a ContentControl

MainWindow: (Define the views you wish to visualize as resources)

<Window.Resources>
    <DataTemplate DataType="{x:Type viewModels:SystemPCViewModel}">
        <controls:SystemPCControl/>
    </DataTemplate>
    <DataTemplate DataType="{x:Type viewModels:ChipPCViewModel}">
        <controls:ChipPCControl/>
    </DataTemplate>
    </ResourceDictionary>

</Window.Resources>

<Grid>
   <ContentControl Content="{Binding CurrentView}"/>
</Grid>

ViewModel: (can't get much simpler)

public ViewModelBase CurrentView
{
    get { return currentView; }
    set { Set(() => CurrentView, ref currentView, value); }
}

And there you go, you can change your views by setting the view model for the controls you defined in your MainWindow

private void OnCommandExecuted()
{
    CurrentView = someViewModel;
}

private void OnAnotherCommandExecuted()
{
    CurrentView = anotherViewModel;
}

HTH!

like image 94
bas Avatar answered Oct 17 '25 01:10

bas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!