【问题标题】:WPF Datatemplating an ItemsControlWPF 数据模板和 ItemsControl
【发布时间】:2009-01-03 09:30:21
【问题描述】:

我有一个ItemsControl,其ItemsSource 在运行时绑定到ObservableCollection<Component>。我已经为 Component 类型定义了一个数据模板,它工作正常。

现在Component 有一个ObservableCollection<Control>,我想在我的Component Datatemplate 中添加另一个ItemsControl 来呈现所有控件。 Control 这是我自己的自定义对象,与 wpf 控件无关。

有不同类型的控件,因此我尝试使用ItemTemplateSelector 为每种类型选择正确的模板。在下面的示例中,为了保持较小,我只展示了一个模板"RWString",我发现它使用MyControlTemplateSelector 中的FindResource 覆盖SelectTemplate。但是SelectTemplate 永远不会被调用(使用断点检查)。我的 xaml 有问题吗?

<ItemsControl.Resources>
    <src:MyControlTemplateSelector x:Key="XSelector" />
    <DataTemplate DataType="{x:Type src:Component}"  >
        <Expander Visibility="{Binding Path=Show}">
                <ItemsControl ItemsSource="{Binding Path=Contrls}" 
                          ItemTemplateSelector="{StaticResource XSelector}">
                <ItemsControl.Resources>
                    <DataTemplate x:Key="RWstring" >
                        <TextBlock Text="{Binding Path=Label}"/>
                    </DataTemplate>
                </ItemsControl.Resources>
                <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate><WrapPanel /></ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
            </ItemsControl>
        </Expander>
    </DataTemplate>
</ItemsControl.Resources>

更新: Contrls 不是错字,只是我使用了一个愚蠢的命名系统。 ContrlsObservableCollection&lt;Control&gt; 类型的组件的属性。另外,我尝试使用ItemsTemplateSelector 的原因是ObservableCollection&lt;Control&gt; 包含泛型类型的对象,如Control&lt;int&gt; Control&lt;string&gt; 等,所有这些都源自Control,显然你不能创建引用泛型类型的数据模板。

Update3:删除了更新 2,因为它不相关。我通过将StaticResource 更改为DynamicResource 使ItemTemplateSelector 工作。但我不知道为什么会这样......

【问题讨论】:

    标签: c# wpf datatemplate itemscontrol


    【解决方案1】:

    我猜这不适用于 StaticResource,因为 Resource 位于 ItemsControl 内,在评估 StaticResources 时可能尚未在加载时创建。

    加载时的动态资源在加载时被评估为表达式,然后在请求时评估为正确的值。

    尝试将资源移到 ItemsControl 之外。

    【讨论】:

    • 谢谢,这就是问题所在。我在运行时创建的 itemscontrol 中创建它
    【解决方案2】:

    在绑定嵌套 ItemsControl 的行中,路径是否正确?现在是“Contrls”,应该是“Controls”吧?

    【讨论】:

    • 是控制。不过,我需要更改该名称……这令人困惑。
    猜你喜欢
    • 1970-01-01
    • 2013-06-15
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 2018-09-27
    • 1970-01-01
    • 2022-01-22
    • 2013-05-23
    相关资源
    最近更新 更多