在App.xaml中使用ResourceDictionary.MergedDictionaries

Ian*_*ink 6 c# xaml xamarin xamarin.forms

在VS2017与Xamarin

在我的app.xaml我有一个MergedDictionary,它引用一个包含我的DataTemplate的xaml.它没有被内容页面识别.如果我将DataTemplate移动到app.xaml它可以正常工作.

如何<ResourceDictionary.MergedDictionaries>识别中定义的StaticResource CellTemplates.xaml

我的App.xaml:

<Application.Resources>
   <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Resources/CellTemplates.xaml"/>
        </ResourceDictionary.MergedDictionaries>
   ....
Run Code Online (Sandbox Code Playgroud)

我的CellTemplates.xaml:

 <ResourceDictionary
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <DataTemplate x:Key="CustomerTemplate">
    <ViewCell Height="100">
          <StackLayout VerticalOptions="FillAndExpand">
     ....
Run Code Online (Sandbox Code Playgroud)

我的内容页面:

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:Muffin"
         x:Class="Muffin.MainPage">
<ScrollView>
    <ListView ItemsSource="{Binding Customers}" 
              HasUnevenRows="True" 
              ItemTemplate="{StaticResource CustomerTemplate}">
    </ListView>
....
Run Code Online (Sandbox Code Playgroud)

Mak*_*man 3

可以创建具有多种合并支持的自定义 ResourceDictionary。

请参阅:https ://github.com/Makeloft/Ace/blob/master/Ace.Zest/Markup/ResourceDictionary.cs

internal static class MergeExtensions
{
    internal static void ForEach<T>(this IEnumerable<T> items, Action<T> action)
    {
        foreach (var item in items) action(item);
    }

    internal static void Merge<TKey, TValue>(this IDictionary<TKey, TValue> targetDictionary,
        IEnumerable<KeyValuePair<TKey, TValue>> sourceItems)
    {
        var targetItems = targetDictionary.ToArray();
        sourceItems.ForEach(i => targetDictionary[i.Key] = i.Value);
        targetItems.ForEach(i => targetDictionary[i.Key] = i.Value); // override merged by local values
    }
}

public class ResourceDictionary : Xamarin.Forms.ResourceDictionary
{
    public ResourceDictionary()
    {
        MergedDictionaries = new ObservableCollection<Xamarin.Forms.ResourceDictionary>();
        MergedDictionaries.CollectionChanged += (sender, args) =>
            (args.NewItems ?? new List<object>()).OfType<Xamarin.Forms.ResourceDictionary>()
            .ForEach(this.Merge);
    }

    public ObservableCollection<Xamarin.Forms.ResourceDictionary> MergedDictionaries { get; }
}
Run Code Online (Sandbox Code Playgroud)

用法

<Application.Resources>
    <m:ResourceDictionary>
        <m:ResourceDictionary.MergedDictionaries>
            <local:AppConverters />
        </m:ResourceDictionary.MergedDictionaries>

        <AnotherResource x:Key="Key1" />
    </m:ResourceDictionary>
</Application.Resources>
Run Code Online (Sandbox Code Playgroud)