gpt4 book ai didi

c# - 在 App.xaml 中使用 ResourceDictionary.MergedDictionaries

转载 作者:太空狗 更新时间:2023-10-29 21:37:48 25 4
gpt4 key购买 nike

在 VS2017 中使用 Xamarin

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

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

我的 App.xaml:

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

我的 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">
....

我的内容页面:

<?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>
....

最佳答案

可以创建具有多个合并支持的自定义 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; }
}

用法

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

<AnotherResource x:Key="Key1" />
</m:ResourceDictionary>
</Application.Resources>

关于c# - 在 App.xaml 中使用 ResourceDictionary.MergedDictionaries,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44640549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com