【问题标题】:ItemControl DataTemplate with UIElement list带有 UIElement 列表的 ItemsControl DataTemplate
【发布时间】:2020-03-16 17:05:52
【问题描述】:

我正在尝试开发以特定方式排列多个 UIElement 的用户控件库。我使用 ItemControl 来显示 UIElements 列表。我想用 Stack 包围项目控制中的每个项目。 我想或多或少地以这种方式使用我的图书馆。

  <pcLayouts:ListLayout>

      <pcLayouts:ListLayout.ParentItems>
          <TextBlock Width="145">1</TextBlock>
          <TextBlock>2</TextBlock>
          <TextBlock>3</TextBlock>
      </pcLayouts:ListLayout.ParentItems>

   </pcLayouts:ListLayout>


我在支持类 ListLayout cs 和 xaml 文件中声明了依赖属性。

        public static readonly DependencyProperty ParentItemsProperty = DependencyProperty.Register(
            "ParentItems", typeof(ObservableCollection<UIElement>), typeof(ColumnLayout),
            new PropertyMetadata(new ObservableCollection<UIElement>()));
...
        public ObservableCollection<UIElement> ParentItems
        {
            get { return (ObservableCollection<UIElement>)GetValue(ParentItemsProperty); }
            set
            {
                SetValue(ParentItemsProperty, value);
                OnPropertyChanged();
            }
        }
    <StackPanel x:Name="MainPanel" Orientation="Vertical">
        <ItemsControl ItemsSource="{Binding ParentItems, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}" >
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel />
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                        <WHAT SHOULD I PUT HERE??/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </StackPanel>

绑定到Binding ParentItems, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}} 时似乎根本没有使用DataTemplate。我该如何使用这个数据模板还是有其他方法?

【问题讨论】:

    标签: wpf itemscontrol


    【解决方案1】:

    这是因为ItemsControl.IsItemItsOwnContainerOverrideUIElement 返回true。通常使用 ContentPresenter 来生成 DataTemplate。

    如果您坚持使用 DataTemplate,则创建一个派生自 ItemsControl 的新类并覆盖 IsItemItsOwnContainerOverride 以返回 false。

    【讨论】:

    • 感谢重载解决了问题,尽管您似乎暗示这种风格不是首选。想指出更合适的方法吗?
    • 这没有什么问题,但通常数据模板用于为数据类型生成 UIElements(比如我有一个字符串,我会有一个 DataTemplate 来生成一个 TextBlock)。如果你知道你的 UIElement 的类型,你可以使用 ItemContainerStyle,或者你可以使用 ItemContainerStyleSelector。
    猜你喜欢
    • 2016-08-01
    • 1970-01-01
    • 2011-09-23
    • 2010-09-30
    • 1970-01-01
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    • 2015-03-25
    相关资源
    最近更新 更多