【问题标题】:Send UserControl to view to display dynamically发送 UserControl 到 view 动态显示
【发布时间】:2015-07-09 19:46:03
【问题描述】:

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

我正在尝试通过我的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,并在此控件中继承。

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

感谢您的指导。

【问题讨论】:

    标签: c# wpf mvvm dialog


    【解决方案1】:

    这可以使用 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 将是用户控件,用于容纳应该对应于这些 ViewModel 类型中的每一个的 UI。

    【讨论】:

      猜你喜欢
      • 2015-03-10
      • 1970-01-01
      • 2016-01-12
      • 2016-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-27
      • 1970-01-01
      相关资源
      最近更新 更多