如何在两个contentpresenter之间切换以绑定到两个单独的contenttemplate和内容?

时间:2019-09-12 19:11:43

标签: c# wpf mvvm

我想要两个绑定了两个内容模板和内容模板的内容表示器。只想显示绑定不为空的contentpresenter

<UserControl.Resources>
    <DataTemplate x:Key="AddressModelTemplate">
        <Grid Background="White">
            <Grid.RowDefinitions>
                <RowDefinition Height="60"/>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="40"/>
            </Grid.RowDefinitions>
            <Label Content="{Binding ElementName=userControl, Path=DataContext.LabelText}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
            <Label Grid.Row="1" Content="Adres" Margin="7"/>
            <TextBox Grid.Row="2" Text="{Binding Address, UpdateSourceTrigger=PropertyChanged}" Margin="7"/>
            <Label Grid.Row="3" Content="Phone" Margin="7"/>
            <TextBox Grid.Row="4" Text="{Binding PhoneNumber, UpdateSourceTrigger=PropertyChanged}" Margin="7"/>
            <StackPanel Grid.Row="7" Orientation="Horizontal" HorizontalAlignment="Right">
                <Button Content="Zapisz" Margin="7" Width="80" Command="{Binding ElementName=userControl, Path=DataContext.SaveCommand}"/>
                <Button Content="Anuluj" Margin="7" Width="80" Command="{Binding ElementName=userControl, Path=DataContext.CancelCommand}"/>
            </StackPanel>
        </Grid>
    </DataTemplate>
    <DataTemplate x:Key="ModelTemplate">
        <Grid >
            <Label Content="Only for show test"/>
        </Grid>
    </DataTemplate>

</UserControl.Resources>
<ContentPresenter Content="{Binding AddressModel}" ContentTemplate="{StaticResource AddressModelTemplate}"/>
<ContentPresenter Content="{Binding Model}" ContentTemplate="{StaticResource ModelTemplate}"/>

我尝试了两个这样的contentpresenter,但是不起作用。

AddressModelModel只是用于绑定的模型,所以我不显示它

1 个答案:

答案 0 :(得分:0)

这可以通过单个ContentPresenter来实现,而您无需显式设置ContentTemplate。将其Content属性绑定到包含Model或AddressModel的视图模型属性。

在设置其DataType属性而不是分配x:Key时会自动选择适当的DataTemplate:

<UserControl.Resources>
    <DataTemplate DataType="{x:Type local:AddressModel}">
        ...
    </DataTemplate>
    <DataTemplate DataType="{x:Type local:Model}">
        ...
    </DataTemplate>
</UserControl.Resources>
...
<ContentPresenter Content="{Binding ModelOrAddressModel}"/>