在WPF中重用XAML

本文关键字:XAML WPF | 更新日期: 2023-09-27 18:15:54

我有一些XAML我想重用。我可以很容易地创建一个自定义控件并使用它,但我宁愿不这样做。以下是我尝试过的:

    <Window.Resources>
    <Expander x:Key="Namespacer" x:Shared="False" Name="NS"  Background="SkyBlue">
        <StackPanel Name="ClientArea" Margin="20,0,20,0">
            <StackPanel Name="Usings" Grid.Row="0" Height="Auto"></StackPanel>
            <StackPanel Name="Structs" Grid.Row="1" Height="Auto"></StackPanel>
            <StackPanel Name="Classes" Grid.Row="2" Height="Auto"></StackPanel>
            <StackPanel Name="IFaces" Grid.Row="3" Height="Auto"></StackPanel>
            <StackPanel Name="Delegates" Grid.Row="4" Height="Auto"></StackPanel>
            <StackPanel Name="Enums" Grid.Row="5" Height="Auto"></StackPanel>
            <StackPanel Name="Nested" Grid.Row="6" Height="Auto"></StackPanel>
        </StackPanel>
    </Expander>
</Window.Resources>
<StackPanel>
    <ContentControl Name="N1" Content="{StaticResource Namespacer}" />
</StackPanel>

现在,我想这样做:

this.N1.Header = "SomeTitle.Namespace1";

并且还能够以类似的方式向N1中的堆栈面板添加新的XAML块。如何做到这一点?

在WPF中重用XAML

你可以这样做:

((Expander)(this.N1.Content)).Header = "SomeTitle.Namespace1";

但这很难看。我建议切换到数据绑定。下面是一个例子。

首先,这里有一个数据类,它的结构我想你会喜欢:

  public partial class MainWindow : Window
  {
    public class MyData
    {
      public string ItemTitle { get; set; }
      public IList<string> Usings { get; set; }
      public IList<string> Structs { get; set; }
    }
    public class MyViewModel
    {
      public IList<MyData> MyBoundData { get; set; }
    }
    public MainWindow()
    {
      var d1 = new MyData{
        ItemTitle = "thing1",
        Usings = new[]{"a", "b"}
      };
      var d2 = new MyData{
        ItemTitle = "thing2",
        Structs = new[]{"c","d"}
      };
      this.DataContext = new MyViewModel{
        MyBoundData = new[]{ d1, d2}
      };
      InitializeComponent();
    }
  }

这里是一个绑定到data的items控件:

<Window x:Class="WpfApplication1.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">
  <Grid>
    <ItemsControl ItemsSource="{Binding MyBoundData}" Focusable="False">
      <ItemsControl.ItemTemplate>
        <DataTemplate>
          <Expander Header="{Binding ItemTitle}" Background="SkyBlue">
            <StackPanel>
              <Expander Header="Usings"  Background="SkyBlue">
                <ItemsControl ItemsSource="{Binding Usings}"/>
              </Expander>
              <Expander Header="Structs" Background="SkyBlue">
                <ItemsControl ItemsSource="{Binding Structs}"/>
              </Expander>
            </StackPanel>
          </Expander>
        </DataTemplate>
      </ItemsControl.ItemTemplate>
    </ItemsControl>
  </Grid>
</Window>

注意items控件有一个DataTemplate对应于你的"Namespacer" xaml块。当然,如果您想在多个ItemsControl中使用它,您可以像在示例中那样将DataTemplate块移动到窗口资源中。