我在UI上有几个标签,我需要在每个标签上显示以下内容:
<StackPanel Orientation="Horizontal">
<Button Content="<" Command="{Binding MoveToPreviousCommand}" />
<TextBlock Text="{Binding SelectedItem.Name}" />
<Button Content=">" Command="{Binding MoveToNextCommand}" />
</StackPanel>
有没有办法避免在XAML中为每个选项卡复制此代码,只需在参考资料中指定上述内容一次并指向每个选项卡下的该资源?
答案 0 :(得分:3)
使用ContentControl
<Window.Resources>
<StackPanel x:Key="Content" x:Shared="False" Orientation="Horizontal">
<Button Content="<" Command="{Binding MoveToPreviousCommand}" />
<TextBlock Text="{Binding SelectedItem.Name}" />
<Button Content=">" Command="{Binding MoveToNextCommand}" />
</StackPanel>
<DataTemplate x:Key="template1">
<StackPanel Orientation="Horizontal">
<Button Content="<" Command="{Binding MoveToPreviousCommand}" />
<TextBlock Text="{Binding SelectedItem.Name}" />
<Button Content=">" Command="{Binding MoveToNextCommand}" />
</StackPanel>
</DataTemplate>
</Window.Resources>
<StackPanel>
<ContentControl Content="{StaticResource Content}"></ContentControl>
<ContentControl Name="contCtrl" ContentTemplate="{StaticResource template1}" Content="This is the content of the content control."/>
</StackPanel>
使用usercontrol
<UserControl x:Class="WpfApplication2.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<StackPanel Orientation="Horizontal">
<Button Content="<" Command="{Binding MoveToPreviousCommand}" />
<TextBlock Text="{Binding SelectedItem.Name}" />
<Button Content=">" Command="{Binding MoveToNextCommand}" />
</StackPanel>
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
xmlns:local="clr-namespace:WpfApplication2">
<Grid>
<local:UserControl1></local:UserControl1>
</Grid>