【问题标题】:WPF Custom Control derived from ItemsControl fails to display bound data从 ItemsControl 派生的 WPF 自定义控件无法显示绑定数据
【发布时间】:2011-07-12 09:59:45
【问题描述】:

我创建了一个名为 MovableItemsControl 的自定义控件,它继承自 ItemsControl,以覆盖 GetContainerForItemOverride() 方法。我的问题是绑定集合中的所有对象都没有显示。目前,我正在绑定到字符串的 OberservableCollection,当我查看调试器时,我可以看到它们位于 ItemsSource 中。

自定义控件如下图:

public class MovableItemsControl : ItemsControl
{
    static MovableItemsControl()
    {          
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MovableItemsControl), new FrameworkPropertyMetadata(typeof(MovableItemsControl)));
    }

    /// <summary>
    /// Wraps each content object added to the ItemsControl in a NodeWrapper
    /// </summary>
    protected override DependencyObject GetContainerForItemOverride()
    {
        NodeWrapper nodeWrapper = new NodeWrapper();            
        return nodeWrapper;
    }

    protected override bool IsItemItsOwnContainerOverride(object item)
    {
        return item is NodeWrapper;
    }
}

NodeWrapper 是一个 UserControl,由一个从 Thumb (MoveThumb) 派生的自定义控件和一个 Label(Label 仅用于测试)组成。

    <Style TargetType="{x:Type local:MovableItemsControl}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:MovableItemsControl}">
                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>   

【问题讨论】:

    标签: wpf wpf-controls binding


    【解决方案1】:

    您是否在包含控件的项目的 Generic.xaml 文件中使用 ControlTemplate 为 MoveableItemsControl 创建了默认样式?如果不是,则控件在加载时不会呈现任何内容。

    更新
    ItemsControl 的 ControlTemplate 需要包含 ItemsPresenter 作为要注入的项目的占位符(类似于 ContentControl 的 ContentPresenter)。您当前的模板只有一个空边框。

    【讨论】:

    • 我已经创建了一个默认样式。我已将其编辑到我的问题中:
    【解决方案2】:

    我认为您在样式 ControlTemplate Border 中也缺少:
    a) 一个 ItemPresenter(例如 &lt;ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/&gt;)或
    b) IsItemsHost 设置为 true 的面板(例如 &lt;StackPanel IsItemsHost="True"/&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-24
      • 1970-01-01
      • 2016-05-11
      相关资源
      最近更新 更多