将SortedList或Dictionary添加到ResourceDictionary我试过这个,但我不知道该怎么做:***SortedList很简单,因为它不是通用的。如果一个类实现了IDictionary,您可以通过将它们定义为具有x:Key的子级来添加值,以设置应将它们添加到字典中的键。xmlns:col="clr-namespace:System.Collections;assembly=mscorlib"LoremIpsumDolorSititemkey在这里是一个字符串,要获得一个实际的int,你可以使用自定义标记扩展将字符串解析为int,或者First将键定义为资源:0123LoremIpsumDolorSit那么绑定就变得更复杂了,因为索引器值需要显式转换为int,否则会被解释为字符串。由于实现细节,您不能省略Path=。字典不是那么容易,因为它们是通用的,并且(目前)没有简单的内置方法在XAML中创建通用对象。但是,使用标记扩展可以通过反射创建通用对象。在此类扩展上实现IDictionary还允许您填充新创建的实例。这是一个非常粗略的例子:publicclassDictionaryFactoryExtension:MarkupExtension,IDictionary{publicTypeKeyType{get;放;}publicTypeValueType{get;放;私人IDictionary_dictionary;privateIDictionaryDictionary{get{if(_dictionary==null){vartype=typeof(Dictionary);vardictType=type.MakeGenericType(KeyType,ValueType);_dictionary=(IDictionary)Activator.CreateInstance(dictType);}返回_字典;}}publicoverrideobjectProvideValue(IServiceProviderserviceProvider){returnDictionary;}publicvoidAdd(objectkey,objectvalue){if(!KeyType.IsAssignableFrom(key.GetType()))key=TypeDescriptor.GetConverter(KeyType).ConvertFrom(key);Dictionary.Add(键,值);}#region其他接口成员publicvoidClear(){thrownewNotSupportedException();}publicboolContains(objectkey){thrownewNotSupportedException();}//#endregion}LoremIpsumDolorSit由于将类型化实例作为键传递有点痛苦,我选择在IDictionary.Add中进行转换,然后将值添加到内部字典后(这可能会导致某些类型的问题)因为字典本身是有类型的,所以绑定不需要强制转换。以上就是C#学习教程:AddSortedListorDictionarytoResourceDictionary分享的全部内容。如果对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
