WPF - 使用DataTemplates将数据绑定到StackPanel [英] WPF - Databind to a StackPanel using DataTemplates

查看:804
本文介绍了WPF - 使用DataTemplates将数据绑定到StackPanel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我修改了我的问题,因为在尝试过程中改变了焦点。
我将问题缩小到以下...

I've modified my question since it has changed focus when trying things out. I narrowed the problem down to the following...

我尝试将所选的TreeView项目绑定到StackPanel(或者其他可以保持用户控件)。此容器将显示UserControl,具体取决于所选项目的类型。

I try to bind the selected Item of a TreeView to a StackPanel (or some other container that can hold User Controls). This container will then display a UserControl, depending on the type of the selected item.

这是StackPanel的xaml(treeview和stackpanel都在同一个窗口中= =>不同的网格列)

Here is the xaml of the StackPanel (both treeview and stackpanel are in the same window ==> different grid column)

<StackPanel Grid.Column="2" MinWidth="500" DataContext="{Binding ElementName=myTree, Path=SelectedItem, Mode=OneWay}">
    <StackPanel.Resources>
        <DataTemplate DataType="{x:Type mvTypes:MyTypeA}">
            <controls:UserControlA DataContext="{Binding}" />
        </DataTemplate>
        <DataTemplate DataType="{x:Type mvTypes:MyTypeB}">
            <controls:UserControlB DataContext="{Binding}" />
        </DataTemplate>
    </StackPanel.Resources>
</StackPanel>

当我将用户控件直接放在堆叠面板(不在资源中)时,它会显示它所选对象作为其数据文本。
如果我放置一个TextBox,它将显示所选项目的正确类型。

When I place a user control directly under the stackpanel (not in the resources), it displays it with the selected object as their datacontext. Idem if I place a TextBox in it, it will show the correct type of the selected item.

<TextBox Name="textBox1" Text="{Binding}" />

由于某些原因,将其放在DataTemplate中(即使没有设置DataType)也不会显示任何内容。

For some reason, placing it within a DataTemplate (even without setting the DataType) results in nothing to display.

任何建议。我正在想,也许一个StackPanel不是正确的控制,虽然我似乎找不到其他适合作为这样的容器的控件。

Any sugestions. I'm thinking that maybe a StackPanel is not the right control for this, though I can't seem to find other controls that look suitable as containers like this.

谢谢

推荐答案

将您的示例中的StackPanel替换为ContentPresenter,而不是DataContext设置Content属性。这应该是正常的。

Replace the StackPanel in your example with ContentPresenter and instead of DataContext set the Content property. That should work.

这篇关于WPF - 使用DataTemplates将数据绑定到StackPanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆