Re-using UI in WPF from a Resource

穿精又带淫゛_ 提交于 2019-12-11 12:59:14

问题


I have a several tabs on UI where on each tab I need the below:

<StackPanel Orientation="Horizontal">
     <Button Content="&lt;" Command="{Binding MoveToPreviousCommand}" />
     <TextBlock Text="{Binding SelectedItem.Name}" />
     <Button Content="&gt;" Command="{Binding MoveToNextCommand}" />
</StackPanel>

Is there a way to avoid replicating this code in XAML for each tab by specifying the above for example in the Resources only once and pointing into that resource under each tab?


回答1:


Using ContentControl

 <Window.Resources>       
    <StackPanel x:Key="Content" x:Shared="False" Orientation="Horizontal">
        <Button Content="&lt;" Command="{Binding MoveToPreviousCommand}" />
        <TextBlock Text="{Binding SelectedItem.Name}" />
        <Button Content="&gt;" Command="{Binding MoveToNextCommand}" />
    </StackPanel>

    <DataTemplate x:Key="template1">
        <StackPanel  Orientation="Horizontal">
            <Button Content="&lt;" Command="{Binding MoveToPreviousCommand}" />
            <TextBlock Text="{Binding SelectedItem.Name}" />
            <Button Content="&gt;" 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>

using 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="&lt;" Command="{Binding MoveToPreviousCommand}" />
        <TextBlock Text="{Binding SelectedItem.Name}" />
        <Button Content="&gt;" 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>



来源:https://stackoverflow.com/questions/24698833/re-using-ui-in-wpf-from-a-resource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!