从资源重用 WPF 中的 UI [英] Re-using UI in WPF from a Resource

查看:31
本文介绍了从资源重用 WPF 中的 UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 UI 上有几个选项卡,在每个选项卡上我需要以下内容:

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>

有没有办法避免在 XAML 中为每个选项卡复制此代码,方法是仅在资源中指定上述示例一次并在每个选项卡下指向该资源?

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?

推荐答案

使用 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>

使用用户控件

<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>

这篇关于从资源重用 WPF 中的 UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆