WPF Custom Control derived from ItemsControl fails to display bound data
I've created a custom control called MovableItemsControl, inheriting from ItemsControl, in order to override the GetContainerForItemOverride() method. My problem is that none of the objects in the bound collection are displaying. Currently, I'm binding to an OberservableCollection of strings, and I can see that they're in ItemsSource when I look through the debugger.
The custom control is shown below:
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 is a UserControl consisting of a custom control derived from Thumb (MoveThumb) and a Label (the Label is just for testing).
<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开发者_高级运维>
Have you created the default Style for MoveableItemsControl with a ControlTemplate in the Generic.xaml file of the project containing the control? If not, there's nothing for the control to render when it loads.
UPDATE
The ControlTemplate for an ItemsControl needs to contain an ItemsPresenter as a placeholder for the items to be injected (similar to ContentPresenter for ContentControl). Your current template only has an empty Border.
I think you are missing inside your style ControlTemplate Border either:
a) An ItemPresenter (eg <ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
) OR
b) A pannel with IsItemsHost set true (eg <StackPanel IsItemsHost="True"/>
)
精彩评论