WPF:类似的xaml

时间:2014-08-17 15:03:46

标签: wpf xaml datatemplate

所以我有一些类似的窗口,他们的xamls是相同的。显然重复的代码并不好。我希望我的Windows只从文件共享xaml。我创建了包含常见xaml的DataTepmlate并将其放入ResourceDictionary中。但我不知道如何将DataTemplate从资源字典放入xaml文件。

我的datatemplate:

<UserControl x:Class="PeriodicTable.View.CollectionViews.CollectionTemplate"
             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">
    <Grid>
        <ListBox  Name="Lst" ItemsSource="{Binding Entity}"  
                  HorizontalContentAlignment="Stretch" 
                  Grid.IsSharedSizeScope="True" >

              <!-- lots and lots of code -->

        </ListBox>
    </Grid>
</UserControl>

我的Resources.xaml:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:collectionViews="clr-namespace:PeriodicTable.View.CollectionViews"
                    xmlns:collectionViewModels="clr-namespace:PeriodicTable.ViewModel.ViewModel.CollectionViewModels">

    <DataTemplate x:Key="ComonCollectionTemplate" DataType="{x:Type collectionViewModels:PeriodsCollectionViewModel}" >
        <collectionViews:CollectionTemplate />
    </DataTemplate>
</ResourceDictionary>

我想把我的datatemplate文件放在哪里:

<Window x:Class="PeriodicTable.View.CollectionViews.PeriodCollectionWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="PeriodWindow" Height="350" Width="750" >

    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="../Resources.xaml"/>
        </ResourceDictionary.MergedDictionaries>        
    </ResourceDictionary>

     what i should write here to place my DataTemplate from Resources.xaml?
</Window>

1 个答案:

答案 0 :(得分:0)

使用 ContentControl 并将 ContentTemplate 设置为资源文件中声明的资源。

<ContentControl ContentTemplate="{StaticResource ComonCollectionTemplate}"/>