Reputation: 9394
In my application I have a HierarchicalDataTemplate
which looks like:
<HierarchicalDataTemplate DataType="{x:Type model:ParentDisplayTreeItem}" ItemsSource="{Binding Children}">
<CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<CheckBox.Content>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="16"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Image Grid.Column="0" Source="{Binding Image}" VerticalAlignment="Center"/>
<TextBlock Grid.Column="1" Text="{Binding Display}" VerticalAlignment="Center" Margin="2,1"/>
</Grid>
</CheckBox.Content>
</CheckBox>
</HierarchicalDataTemplate>
And a DataTemplate
which looks like:
<DataTemplate DataType="{x:Type model:ChildDisplayTreeItem}">
<CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<CheckBox.Content>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="16"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Image Grid.Column="0" Source="{Binding Image}" VerticalAlignment="Center"/>
<TextBlock Grid.Column="1" Text="{Binding Display}" VerticalAlignment="Center" Margin="2,1"/>
</Grid>
</CheckBox.Content>
</CheckBox>
</DataTemplate>
As you can see both have the same content with a CheckBox
.
Is it possible to move the CheckBox
to a resource and use it from there?
I've tried it to provide it as ControlTemplate
in the resources like:
<ControlTemplate x:Key="CheckBoxControlTemplate">
<CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<CheckBox.Content>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="16"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Image Grid.Column="0" Source="{Binding Image}" VerticalAlignment="Center"/>
<TextBlock Grid.Column="1" Text="{Binding Display}" VerticalAlignment="Center" Margin="2,1"/>
</Grid>
</CheckBox.Content>
</CheckBox>
</ControlTemplate>
And use it like:
<HierarchicalDataTemplate DataType="{x:Type model:ParentDisplayTreeItem}" ItemsSource="{Binding Children}">
<StaticResource ResourceKey="CheckBoxControlTemplate"/>
</HierarchicalDataTemplate>
But I get a compile-error with this approach.
Upvotes: 0
Views: 46
Reputation: 1660
Yes, you can do that. It should look like this.
<HierarchicalDataTemplate DataType="{x:Type model:ParentDisplayTreeItem}"
ItemsSource="{Binding Children}">
<CheckBox Template="{StaticResource CheckBoxControlTemplate}" />
</HierarchicalDataTemplate>
Upvotes: 0