改变主要观察区域

rre*_*ves 0 c# wpf contentcontrol

我想知道如何在按下按钮时在主窗口中创建不同的视图.我不确定正确的术语,所以这阻碍了我的谷歌.

我认为主要的观看区域是内容控件,我可以在事件发生时进行更改.我做了一个小图画来帮助说明我的想法/想法.

任何输入将不胜感激.谢谢! 原油样机

Ank*_*esh 5

使用MVVM方法实现这个senario真的很容易....

为您创建一个ViewModel MainView.然后定义UserControls的ViewModel的属性

例如,您有两个UserControl as FirstView,SecondView然后在ViewModel ViewToLoadProperty类型中创建一个属性ViewModel(通常称为ViewModelBase)

将绑定设置为

        <!--  Panel For Hosting UserControls  -->
        <Border Grid.Column="2">
            <ContentControl Name="userControlContentControl"
                            Content="{Binding Path=ViewToLoadProperty,
                                              }">
                <ContentControl.Resources>
                    <DataTemplate DataType="{x:Type ViewModelLayer:FirstViewModel}">
                        <ViewLayer:FirstView/>
                    </DataTemplate>
                    <DataTemplate DataType="{x:Type ViewModelLayer:SecondViewModel}">
                        <ViewLayer:SecondView />
                    </DataTemplate>
                                        </ContentControl.Resources>
            </ContentControl>
        </Border>
        <!--  Panel For Hosting UserControls  -->
Run Code Online (Sandbox Code Playgroud)

然后单击按钮使用命令将相应的ViewModel Intance设置为此(ViewToLoadProperty)属性...(使用RelayCommannds或类似的东西)

DataTempates 通过根据正确的ViewModel类型选择正确的View,可以完成剩下的工作

如果你正在实现MVVM模式,你可以使用MVVMLight工具包.. :)

  • 我有另一个答案,我仍然给你一个+1.我需要学习MVVM. (2认同)
  • @BalamBalam谢谢...... :) (2认同)