根据组合框中选定的字符串值切换数据模板

发布于 2024-11-26 18:01:49 字数 461 浏览 1 评论 0原文

根据组合框中选定的字符串值,我想在网格内显示红色/蓝色数据模板。

可以在没有 ContentControl 的情况下完成此操作吗?

<UserControl.Resources >

<DataTemplate x:Key="red">
        <TextBox Text="red" />
    </DataTemplate>

    <DataTemplate x:Key="blue">
        <TextBox Text="blue" />
    </DataTemplate>

</UserControl.Resources>

<ComboBox ??? />
<Grid>
   // Show red or blue datatemplate here
</Grid>

Based on a selected string value in the combobox I want to either show red/blue datatempalte inside the grid.

Can this be done without a ContentControl?

<UserControl.Resources >

<DataTemplate x:Key="red">
        <TextBox Text="red" />
    </DataTemplate>

    <DataTemplate x:Key="blue">
        <TextBox Text="blue" />
    </DataTemplate>

</UserControl.Resources>

<ComboBox ??? />
<Grid>
   // Show red or blue datatemplate here
</Grid>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

携余温的黄昏 2024-12-03 18:01:49

为什么不使用 ContentControl?

为了使这项工作简单,我将模板放入一个数组中,然后 ComboBox 可以将其绑定到:

<x:Array x:Key="templates" Type="{x:Type DataTemplate}">
    <DataTemplate>
        <DataTemplate.Resources>
            <sys:String x:Key="DisplayString">Red</sys:String>
        </DataTemplate.Resources>
        <TextBox Text="red" />
    </DataTemplate>

    <DataTemplate>
        <DataTemplate.Resources>
            <sys:String x:Key="DisplayString">Blue</sys:String>
        </DataTemplate.Resources>
        <TextBox Text="blue" />
    </DataTemplate>
</x:Array>
<ComboBox Name="combo" ItemsSource="{StaticResource templates}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Resources[DisplayString]}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>
<Grid>
    <ContentControl ContentTemplate="{Binding SelectedItem, ElementName=combo}" />
</Grid>

Why not use a ContentControl?

To make this work simply i would put the templates in an array, which the ComboBox then can bind to:

<x:Array x:Key="templates" Type="{x:Type DataTemplate}">
    <DataTemplate>
        <DataTemplate.Resources>
            <sys:String x:Key="DisplayString">Red</sys:String>
        </DataTemplate.Resources>
        <TextBox Text="red" />
    </DataTemplate>

    <DataTemplate>
        <DataTemplate.Resources>
            <sys:String x:Key="DisplayString">Blue</sys:String>
        </DataTemplate.Resources>
        <TextBox Text="blue" />
    </DataTemplate>
</x:Array>
<ComboBox Name="combo" ItemsSource="{StaticResource templates}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Resources[DisplayString]}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>
<Grid>
    <ContentControl ContentTemplate="{Binding SelectedItem, ElementName=combo}" />
</Grid>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文