wpf 如何切换contenttemplate依赖于哪个视图模型对象?

smdncfj3  于 2022-11-18  发布在  其他
关注(0)|答案(2)|浏览(114)

如何设置当特定的视图模型设置时显示哪个视图?我看了这个关于数据模板的解释,但是我还是不明白。因为它没有显示所有使用数据模板作为切换视图的代码。

<Window x:Class="Pandora.Views.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vm="clr-namespace:Pandora.ViewModels"
        Title="Pandora" Height="350" Width="525">
    <Window.ContentTemplate>
            <DataTemplate DataType="{x:Type vm:IndexViewModel}">
                <TextBlock>Index Content</TextBlock>
            </DataTemplate>

            <DataTemplate DataType="{x:Type vm:DashboardViewModel}">
                <TextBlock>Dashboard Content</TextBlock>
            </DataTemplate>
    </Window.ContentTemplate>
</Window>

C#语言

using Pandora.ViewModels;

namespace Pandora.Views;

public partial class MainWindow
{
    public MainWindow()
    {
      InitializeComponent();
      DataContext = new IndexViewModel();
    }
}
8yparm6h

8yparm6h1#

要使Window显示任何内容,它应该具有一些Content(空Window模板包含<Grid></Grid>元素)。只需使用绑定从DataContext复制Content。
在您的示例中,您希望显示元素,这些元素没有自己的可视表示(IndexViewModel、DashboardViewModel),因此它们需要自定义DataTemplate。

<Window x:Class="Pandora.Views.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vm="clr-namespace:Pandora.ViewModels"
        Title="Pandora" 
        Content="{Binding}"
        Height="350" Width="525">
    <Window.Resources>
        <DataTemplate DataType="{x:Type vm:IndexViewModel}">
            <TextBlock>Index Content</TextBlock>
        </DataTemplate>

        <DataTemplate DataType="{x:Type vm:DashboardViewModel}">
            <TextBlock>Dashboard Content</TextBlock>
        </DataTemplate>
    </Window.Resources>
</Window>

或使用单独元素插入自定义内容的更常见方法:

<Window x:Class="Pandora.Views.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vm="clr-namespace:Pandora.ViewModels"
        Title="Pandora" 
        Height="350" Width="525">
    <Window.Resources>
        <DataTemplate DataType="{x:Type vm:IndexViewModel}">
            <TextBlock>Index Content</TextBlock>
        </DataTemplate>

        <DataTemplate DataType="{x:Type vm:DashboardViewModel}">
            <TextBlock>Dashboard Content</TextBlock>
        </DataTemplate>
    </Window.Resources>
    <Grid>
         <ContentPresenter Content="{Binding}"/>
         <TextBlock Text="Demo watermark" VerticalAlignment="Center" HorizontalAlignment="Center" IsHitTestVisible="False"/>
    </Grid>
</Window>
wmvff8tz

wmvff8tz2#

您必须将IndexViewModelDashboardViewModel例项指派给Window.Content属性。ContentTemplate会套用至Content属性目前值的数据对象:

public partial class MainWindow
{
    public MainWindow()
    {
      InitializeComponent();
      this.Content = new IndexViewModel();
    }
}

相关问题