将 UserControl 发送到视图以动态显示

Send UserControl to view to display dynamically

我正在尝试首次涉足 WPF 和 MVVM。我需要一个用作伪对话框的用户控件 - 它 'dialogs' 在它所在的应用程序部分(选项卡)上,但允许用户仍然切换到应用程序的其他区域。

我正在尝试通过我的 TabDialog UserControl 来完成此操作。目前它看起来像:

<Grid
     Visibility="{Binding ShowAvailable, Converter={StaticResource BoolToVis}}">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <StackPanel
        Grid.Row="0"
        Grid.Column="0"
        Grid.RowSpan="3"
        Grid.ColumnSpan="3"
        Background="black"
        Opacity=".5"
        />

    <Label Background="Red" 
           Grid.Row="1"
           Grid.Column="1"
           Content="{Binding ShowAvailable}"></Label>
</Grid>

其中 ShowAvailable 是父 DataContext 上的 Bool,并在此控件中继承。

我现在的问题是,因为我想为不同的 'dialog' 视图重新使用此控件,所以我想传递它应该显示的视图(将替换 Label)。如何将父 ViewModel 定义的用户控件发送到此视图并显示它?

感谢您的指导。

这可以使用 DataTemplates 和 ContentControls 来完成。由于 Content 控件未指定 ContentTemplate,因此它根据绑定到的视图模型的类型确定哪个 DataTemplate。因此,要更改正在使用的视图,只需更改绑定到的对象的类型即可。

<Grid Visibility="{Binding ShowAvailable, Converter={StaticResource BoolToVis}}">
    <Grid.Resources>
        <DataTemplate DataType="LabelViewModel">
            <wpfApplication1:MyUserControl />
        </DataTemplate>
        <DataTemplate DataType="NonLabelViewModel">
            <wpfApplication1:OtherUserControl />
        </DataTemplate>
    </Grid.Resources>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <StackPanel
    Grid.Row="0"
    Grid.Column="0"
    Grid.RowSpan="3"
    Grid.ColumnSpan="3"
    Background="black"
    Opacity=".5"
    />
    <ContentControl Content="{Binding ViewModelObject}" />
</Grid>

LabelViewModel 和 NonLabelViewModel 将是您要定义的 ViewModel,(并添加到网格绑定到的父视图模型,作为 属性 命名的 ViewModelObject ) 和 MyUserControl 和 OtherUserControl 将是用户控件来容纳 UI 应该对应于这些 ViewModel 类型中的每一个。