在WPF中重用XAML

时间:2015-10-04 23:54:01

标签: c# wpf xaml

我想要重用一些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";

并且能够以类似的方式将新的XAML块添加到N1中的堆栈面板中。如何实现?

1 个答案:

答案 0 :(得分:2)

嗯,你可以这样做:

((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();
    }
  }

这是一个绑定到我们数据的项控件:

<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控件具有与“Namespacer”xaml块相对应的DataTemplate。当然,如果你想在多个ItemsControl中使用它,你可以将DataTemplate块移动到你的示例中的窗口资源中。