在Windows Phone中的ResourceDictionary中访问DataTemplate

时间:2012-12-17 04:13:13

标签: windows-phone-7 datatemplate resourcedictionary

我在ResourceDictionary'style1.xaml'中定义了一个DataTemplate:

<ResourceDictionary
    xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >

    <DataTemplate x:Key="BlogDataTemplate">
        <Grid Margin="0,0,6,20" Width="400" Height="210">
            <Grid VerticalAlignment="Bottom" Background="#A6000000">
                <TextBlock Text="{Binding title}" Style="{StaticResource PhoneTextExtraLargeStyle}" Foreground="White" Margin="6" FontSize="25" TextWrapping="Wrap"/>
            </Grid>
        </Grid>
    </DataTemplate>

</ResourceDictionary>

在App.xaml.cs中,我使用以下代码合并ResourceDictionary:

void LoadDictionary()
{
    var dictionaries = Resources.MergedDictionaries;
    string source = string.Empty;
    var themeStyles = new ResourceDictionary { };
    switch (Settings.fontStyle.Value)
    {
        case 0:
            source = String.Format("/app;component/Themes/style1.xaml");
            themeStyles.Source = new Uri(source, UriKind.Relative);
            dictionaries.Add(themeStyles);
            break;
        case 1:
            source = String.Format("/app;component/Themes/style2.xaml");
            themeStyles.Source = new Uri(source, UriKind.Relative);
            dictionaries.Add(themeStyles);
            break;
        default: break;
    }
}

通过调试我可以确保已合并了style1.xaml,然后在MainPage.xmal中我有一个Listbox,我将ItemTemplate定义为

 <ListBox x:Name="listbox" ItemsSource="{Binding}" CacheMode="BitmapCache" ItemTemplate="{StaticResource BlogDataTemplate}"/>

但是当我部署应用程序时,它导致了“未指定的错误”。

那么如何在Windows Phone中的ResourceDictionary中访问DataTemplate?

提前致谢。

1 个答案:

答案 0 :(得分:2)

尝试在App.xaml中将ResourceDictionary与Xaml合并,而不是使用LoadDictionary代码(在App.xaml中,在Application.Resources中):

    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Themes/style1.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>