首页 > 解决方案 > 如何在 Content Presenter 中设置我的视图

问题描述

我目前正在开发基于数据库的工作应用程序,并且正在努力将 ViewModel 方法连接到我的视图。这是我到目前为止所得到的:

public class MainViewModel : BaseViewModel
{
    public ICommand SwitchViewsCommand { get; private set; }
    public MainViewModel()
    {
        SwitchViewsCommand = new RelayCommand((parameter) => CurrentView = (UserControl)Activator.CreateInstance(parameter as Type));
    }
    private UserControl _currentView;
    public UserControl CurrentView
    {
        get
        {
            return _currentView;
        }
        set
        {
            if (value != _currentView)
            {
                _currentView = value;
                OnPropertyChanged("CurrentView");
            }
        }
    }
}

这是我的 MainViewModel 并遵循我的 Xaml 代码

<Window x:Class="sKillPase.View.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:viewmodels="clr-namespace:sKillPase.Core.ViewModels;assembly=sKillPase.Core" xmlns:view="clr-namespace:sKillPase.View"
    xmlns:local="clr-namespace:sKillPase.View"
    d:DataContext="{d:DesignInstance Type=viewmodels:MainViewModel}"
    mc:Ignorable="d"
    Title="MainWindow" Height="800" Width="1200">
<Grid >
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="150" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="80" />
        <RowDefinition Height="*" />
        <RowDefinition Height="20" />
    </Grid.RowDefinitions>
    <Border x:Name="Top" Grid.Column="0" Grid.ColumnSpan="2" Background="Black" ></Border>
    <Border x:Name="Buttons" Grid.Row="1" Grid.RowSpan="2" Background="Black"></Border>
    <Border x:Name="Content" Grid.Row="1" Grid.Column="1" Background="#FF303030"></Border>
    <Border x:Name="Bottom" Grid.Row="2" Grid.Column="1" Background="Black"/>
    <ContentPresenter Grid.Row="1" Grid.Column="1" x:Name="ContentArea" Content="{Binding CurrentView}"/>
    <StackPanel x:Name="ButtonPanel" Margin="5" Grid.Row="1">
        <Button x:Name="Data" 
                Command="{Binding SwitchViewsCommand }" 
                CommandParameter="{x:Type local:DataView}" 
                >
            Daten bearbeiten
        </Button>
        <Button x:Name="Report"
                Command="{Binding SwitchViewsCommand}" 
                CommandParameter="{x:Type viewmodels:ReportViewModel}"
                >
            Report erstellen
        </Button>
    </StackPanel>


</Grid>

所以我的问题是,如果我编译应用程序,Content Presenter 不会显示任何内容。它完全是空的。那么,通过按下两个按钮之一,我可以做些什么来将不同的视图(我声明为用户控件)添加到我的内容演示器?

此外,其中一个视图包含一个数据网格,显示了我的数据库的不同表。因此,如果我必须注意有关数据库的一些问题,请随时说明。

提前致谢 :)

标签: c#wpfmvvm

解决方案


推荐阅读