是否可以在模板中使用模板?
例如,我有以下两个模板:
<HierarchicalDataTemplate
x:Key="RecursiveTemplate"
ItemsSource="{Binding Children}">
<StackPanel Margin="1" Orientation="Horizontal">
<Ellipse Fill="DarkGreen" Width="14" Height="14"/>
<TextBlock
MouseDown="OnTreeMouseDown"
TargetUpdated="OnTargetUpdated"
Visibility="{Binding Editing, Converter={StaticResource visibilityInverter}}"
Margin="5"
Text="{Binding Name}"/>
<TextBox
PreviewKeyDown="OnTreeKeyDown"
Visibility="{Binding Editing, Converter={StaticResource visibilityConverter}}"
Margin="2"
Text="{Binding Name}"/>
</StackPanel>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate
x:Key="ContainerTemplate"
ItemsSource="{Binding Children}">
<StackPanel Margin="1" Orientation="Horizontal">
<Ellipse Fill="DarkBlue" Width="14" Height="14"/>
<TextBlock
MouseDown="OnTreeMouseDown"
TargetUpdated="OnTargetUpdated"
Visibility="{Binding Editing, Converter={StaticResource visibilityInverter}}"
Margin="5"
Text="{Binding Name}"/>
<TextBox
PreviewKeyDown="OnTreeKeyDown"
Visibility="{Binding Editing, Converter={StaticResource visibilityConverter}}"
Margin="2"
Text="{Binding Name}"/>
</StackPanel>
</HierarchicalDataTemplate>
有一段相同的XAML:
<TextBlock
MouseDown="OnTreeMouseDown"
TargetUpdated="OnTargetUpdated"
Visibility="{Binding Editing, Converter={StaticResource visibilityInverter}}"
Margin="5"
Text="{Binding Name}"/>
<TextBox
PreviewKeyDown="OnTreeKeyDown"
Visibility="{Binding Editing, Converter={StaticResource visibilityConverter}}"
Margin="2"
Text="{Binding Name}"/>
是否可以将其移动到资源并按名称引用它,而不是重复它?
答案 0 :(得分:2)
答案似乎是“差不多”
<Style x:Key="textBlockStyle" TargetType="TextBlock">
<Setter Property="Visibility" Value="{Binding Editing, Converter={StaticResource visibilityInverter}}"/>
<Setter Property="Margin" Value="4"/>
<Setter Property="Text" Value="{Binding Name}"/>
<EventSetter Event="MouseDown" Handler="OnTreeMouseDown"/>
</Style>
<Style x:Key="textBoxStyle" TargetType="TextBox">
<Setter Property="Visibility" Value="{Binding Editing, Converter={StaticResource visibilityConverter}}"/>
<Setter Property="Margin" Value="1"/>
<Setter Property="Text" Value="{Binding Name, NotifyOnSourceUpdated=True}"/>
<EventSetter Event="PreviewKeyDown" Handler="OnTreeKeyDown"/>
</Style>
然后模板缩小为
<HierarchicalDataTemplate
x:Key="RecursiveTemplate"
ItemsSource="{Binding Children}">
<StackPanel Margin="1" Orientation="Horizontal">
<Ellipse Fill="DarkGreen" Width="14" Height="14"/>
<TextBlock
Style="{StaticResource textBlockStyle}"/>
<TextBox
SourceUpdated="OnSourceUpdated"
Style="{StaticResource textBoxStyle}"/>
</StackPanel>
</HierarchicalDataTemplate>
但是,请注意,您不能将SourceUpdated放入样式中,因为EventSetter未涵盖