Reputation: 807
We're trying to make a custom control that contains a wrapped section of text boxes for each item in the list bound to it.
Like this:
<ItemsControl x:Name="asdf">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<controls:WrapPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
However, when we turn this into a custom control, it doesn't set the ItemsPanel to a WrapPanel, nor does it do the ItemTemplate either:
<ItemsControl x:Class="SilverlightApplication1.PillTagBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:controls= "clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<controls:WrapPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
It just shows the bound list of items like there was no styling at all:
<ItemsControl x:Name="asdf" />
How do we make the first chunk of XAML into a custom control?
Thanks!
Upvotes: 0
Views: 472
Reputation: 6289
For what you want to do, you don't need a custom control, a style is enough:
<Style x:Key="MyControlStyle" TargetType="ItemsControl">
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<controls:WrapPanel/>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<TextBox Text="{Binding}" />
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
And then at the instance:
<ItemsControl x:Name="asdf" Style="{StaticResource MyControlStyle}" />
If you do need a custom control for other reasons:
Add a constructor like this:
public MyItemsControl()
{
this.DefaultStyleKey = typeof(MyItemsControl);
}
Upvotes: 2