使用xaml中的key创建实例

时间:2017-06-20 12:27:44

标签: c# wpf xaml

鉴于ResourceDictionary

<GroupBox x:Key="Group"
          x:Shared="False">
    <ItemsControl ItemsSource="{Binding Items}">
    ...
    </ItemsControl>
</GroupBox>
<ItemsControl x:Key="Test"
              x:Shared="False"
              ItemsSource="{Binding Items}">
...
</ItemsControl>

ItemsControl内容均相同。是否有可能避免重复相同的xaml(...相当大)?是否可以在Test内创建Group实例。

2 个答案:

答案 0 :(得分:1)

You could use a ContentControl:

<ItemsControl x:Key="Test"
              x:Shared="False"
              ItemsSource="{Binding Items}">
</ItemsControl>
<GroupBox x:Key="Group" x:Shared="False">
    <ContentControl Content="{StaticResource Test}" />
</GroupBox>

Note that the ItemsControl resource must be defined before the GroupBox resource.

As pointed out by @grek40, you could also set the Content property of the GroupBox directly to the ItemsSource resource provided that the GroupBox doesn't contain any other controls.

答案 1 :(得分:1)

Actually, you can directly set the content

<GroupBox x:Key="Group" x:Shared="False" Content="{StaticResource Test}">

I'm not really a fan of x:Shared (bugged me some times), so how about using some DataTemplate instead?

<DataTemplate x:Key="TestTemplate">
    <ItemsControl ItemsSource="{Binding Items}">
        <!-- Whatever it is you have inside... -->
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding}" Background="Yellow"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</DataTemplate>

<GroupBox Content="{Binding}" ContentTemplate="{StaticResource TestTemplate}">
</GroupBox>