Wpf从资源中重用UI元素
在我的界面上有几个选项卡,每个选项卡中都有下面的元素:
<StackPanel Orientation="Horizontal">
<Button Content="<" Command="{Binding MoveToPreviousCommand}" />
<Button Content=">" Command="{Binding MoveToNextCommand}" />
</StackPanel>
有没有办法避免复制此代码到XAML中每个选项卡中,能不能在资源中定义一次上面的元素,每个选项卡都指向UI资源呢?答案是肯定的。
<Window.Resources>
<StackPanel x:Key="Content" Orientation="Horizontal">
<Button Content="<" Command="{Binding MoveToPreviousCommand}" />
<Button Content=">" Command="{Binding MoveToNextCommand}" />
</StackPanel>
<DataTemplate x:Key="template1">
<StackPanel Orientation="Horizontal">
<Button Content="<" Command="{Binding MoveToPreviousCommand}" />
<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>