【问题标题】:How to dynamically change the ControlTemplate based on a property in a ViewModel?如何根据 ViewModel 中的属性动态更改 ControlTemplate?
【发布时间】:2019-01-10 13:35:56
【问题描述】:

我想根据 ViewModel 的属性动态选择 ControlTemplate。我如何实现它。

我在视图中有 2 个 ControlTemplate,在 ViewModel 上有一个布尔属性。基于该属性,我必须在视图中选择并显示我的 ControlTempale 之一。

<Window.Resources>
        <ControlTemplate x:Key="simpleErrorTemplate">
            <TextBox Margin="10,10,10,5" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" Text="T1" />
        </ControlTemplate>
        <ControlTemplate x:Key="detailedErrorTemplate">
            <StackPanel>
                <TextBox Margin="10,10,10,5" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" Text="T2" />
                <TextBox Margin="10,10,10,5" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" Text="T3" />
                <TextBox Margin="10,10,10,5" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" Text="T4" />
            </StackPanel>
        </ControlTemplate>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="50" />
        </Grid.RowDefinitions>
        <ContentControl Grid.Row="0" DataContext="{Binding Report}">
            <ContentControl.Style>
                <Style TargetType="ContentControl">
                    <Setter Property="Template" Value="{StaticResource simpleErrorTemplate}"/>
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding IsTyping}" Value="True">
                            <Setter Property="Template" Value="{StaticResource detailedErrorTemplate}"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </ContentControl.Style>
        </ContentControl>
        <CheckBox Margin="10,0,0,0" Grid.Row="1" x:Name="ChkShowDetails" IsChecked="{Binding IsTyping, Mode=TwoWay,    UpdateSourceTrigger=PropertyChanged}">Show Details</CheckBox>
    </Grid>

所以基于 IsTyping 的值,我想显示我的 ControlTemplate。 如果我直接将元素绑定到 Control 模板,它会起作用,但这不是我的要求。

【问题讨论】:

    标签: wpf xaml controltemplate


    【解决方案1】:

    将数据触发器绑定到正确的DataContext,即与CheckBox绑定的相同:

    <DataTrigger Binding="{Binding DataContext.IsTyping, RelativeSource={RelativeSource AncestorType=ContentControl}}" Value="True">
        <Setter Property="Template" Value="{StaticResource detailedErrorTemplate}"/>
    </DataTrigger>
    

    【讨论】:

    • 感谢您的回复。它工作得很好。
    【解决方案2】:

    我认为你可以做一些更简单的事情

    你需要它来使用ContentControl'sContentTemplateSelector来实现你想要的。

    ContentTemplateSelector 是一个自定义类,它将根据您的数据切换模板。

    这会给你的想法:http://www.wpftutorial.net/datatemplates.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多