【问题标题】:Access DataTemplate in ResourceDictionary in Windows Phone在 Windows Phone 的 ResourceDictionary 中访问 DataTemplate
【发布时间】:2012-12-17 04:13:13
【问题描述】:

我在 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 中我有一个列表框,我将 ItemTemplate 定义为

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

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

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

提前致谢。

【问题讨论】:

    标签: windows-phone-7 datatemplate resourcedictionary


    【解决方案1】:

    尝试通过执行以下操作(在 App.xaml 中的 Application.Resources 中)将 ResourceDictionary 与 App.xaml 中的 Xaml 合并,而不是 LoadDictionary 代码:

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

    【讨论】:

    • 嗨 codechinchilla,我做了你在答案中发布的内容,但它抛出异常找不到名称/键 BlogDataTemplate 的资源如何摆脱这个异常?
    • 嘿 Android_Crazy - 你能发布你的 App.xaml 和你正在使用的资源字典 xaml 吗?
    • 对于社区,您是如何解决问题的?谢谢。
    猜你喜欢
    • 2015-04-27
    • 1970-01-01
    • 1970-01-01
    • 2013-11-28
    • 1970-01-01
    • 1970-01-01
    • 2012-10-26
    • 1970-01-01
    • 2016-01-19
    相关资源
    最近更新 更多