简体   繁体   中英

load user control dynamically in wpf using mvvm

Hi have 2 usercontrol(WPF). I have to load this control according to condition. I have ReadingBookDoubleView.xaml nad ReadingBookDoubleViewpdf.xaml this is my code.

   <UserControl.Resources>
    <DataTemplate DataType="{x:Type viewModels:ReadingBookDoubleVM}">
        <view:ReadingBookDoubleViewPdf/>
    </DataTemplate>
    <DataTemplate DataType="{x:Type viewModels:ReadingBookDoubleVM}">
        <view:ReadingBookDoubleView/>
    </DataTemplate>
</UserControl.Resources>

I have book kind in Viewmodel class which is bind to this view where I am loading the user control. i have to load one control at a time.If book Kind is Pdf then I have load ReadingBookDoubleViewpdf control other wise I have to load ReadingBookDoubleView.

how can I load the control according to condition.

You could use a single DataTemplate with a Trigger:

<UserControl.Resources>
    <DataTemplate DataType="{x:Type viewModels:ReadingBookDoubleVM}">
        <ContentControl x:Name="Presenter" Content="{Binding}">
            <ContentControl.ContentTemplate>
                <DataTemplate>
                    <view:ReadingBookDoubleView />
                </DataTemplate>
            </ContentControl.ContentTemplate>
        </ContentControl>
        <DataTemplate.Triggers>
            <DataTrigger Binding="{Binding Kind}" Value="Pdf">
                <Setter TargetName="Presenter"
                        Property="ContentTemplate">
                    <Setter.Value>
                        <DataTemplate>
                            <view:ReadingBookDoubleViewPdf />
                        </DataTemplate>
                    </Setter.Value>
                </Setter>
            </DataTrigger>
        </DataTemplate.Triggers>
    </DataTemplate>
</UserControl.Resources>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM