2014-07-11 54 views
1

我對UI中的幾個選項卡,每個選項卡上,我需要以下:再使用UI在WPF從資源

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

有沒有辦法避免複製在XAML此代碼爲每個標籤由在資源中只指定一次上面的例子,並在每個選項卡下指向該資源?

回答

2

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

使用用戶控件

enter image description here

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

+0

我通常爲此使用UserControl。 +1 – kenny

+0

使用ContentControl:當StackPanel直接在資源中設置時,它僅在一個選項卡上顯示內容(在XAML中最後定義哪些內容)。在其他選項卡上,ContentControl未顯示任何內容。 – Nuts

+0

使用ContentControl:當使用DataTemplate時,我會在綁定正確後獲得所需的行爲:Command =「{Binding RelativeSource = {RelativeSource AncestorType = {x:Type Window}},Path = DataContext.MoveToPreviousCommand}」 – Nuts