南京网站设计公司哪儿济南兴田德润怎么联系sem推广是什么意思呢
web/
2025/10/7 12:35:01/
文章来源:
南京网站设计公司哪儿济南兴田德润怎么联系,sem推广是什么意思呢,qq网页版登陆,高新网页设计报价WPF ComboBox 使用 ResourceBinding 动态绑定资源键并支持语言切换独立观察员 2021 年 8 月 23 日我们平常在 WPF 中进行资源绑定操作#xff0c;一般就是用 StaticResource 或者 DynamicResource 后面跟上资源的 key 这种形式#xff0c;能满足大部分需求。但是有的时候一般就是用 StaticResource 或者 DynamicResource 后面跟上资源的 key 这种形式能满足大部分需求。但是有的时候我们需要绑定的是代表了资源的 key 的变量也就是动态绑定资源的 key注意和 DynamicResource 区分开比如本文将要演示的支持国际化的场景。这种动态绑定资源 key 的功能在 WPF 中没有被原生支持所以还是得在网上找找解决方法。 最终在 stackoverflow 网站上看到一篇靠谱的讨论帖Binding to resource key, WPF里面几个人分别用 标记扩展、附加属性、转换器 的方式给出了解决方法本文使用的是 Gor Rustamyan 给出的 标记扩展 的方案核心就是一个 ResourceBinding 类代码整理了下下文给出。 先来看看本次的使用场景吧简单来说就是一个下拉框控件绑定了键值对列表显示的是其中的键但是要求是支持国际化多语言如下图 由于要支持多语言所以键值对的键不是直接显示的值而是显示值的资源键/// summary
/// 时间列表
/// /summary
public ObservableCollectionKeyValuePairstring, int TimeList { get; set; } new ObservableCollectionKeyValuePairstring, int()
{new KeyValuePairstring, int(LockTime-OneMinute, 1),new KeyValuePairstring, int(LockTime-FiveMinute, 5),new KeyValuePairstring, int(LockTime-TenMinute, 10),new KeyValuePairstring, int(LockTime-FifteenMinute, 15),new KeyValuePairstring, int(LockTime-ThirtyMinute, 30),new KeyValuePairstring, int(LockTime-OneHour, 60),new KeyValuePairstring, int(LockTime-TwoHour, 120),new KeyValuePairstring, int(LockTime-ThreeHour, 180),new KeyValuePairstring, int(LockTime-Never, 0),
};字符串资源放在资源字典中 界面 Xaml 代码为xmlns:markupExtensionsclr-namespace:Mersoft.Mvvm.MarkupExtensionsGroupBox Header演示 ComboBox 绑定资源键国际化支持 Height100StackPanel OrientationHorizontalComboBox MinWidth200 MaxWidth400 Height35 Margin10 FontSize18 VerticalContentAlignmentCenterItemsSource{Binding TimeList} SelectedItem{Binding SelectedTime}ComboBox.ItemTemplateDataTemplateTextBlock Text{markupExtensions:ResourceBinding Key}/TextBlock/DataTemplate/ComboBox.ItemTemplate/ComboBoxButton Width100 Command{Binding SwitchCnCmd} 切换中文 /ButtonButton Width100 Command{Binding SwitchEnCmd} 切换英文 /ButtonTextBlock Text{markupExtensions:ResourceBinding SelectedTime.Key} VerticalAlignmentCenter/TextBlock/StackPanel
/GroupBox可以看到给 ComboBox 的 ItemTemplate 设置了一个 DataTemplate里面通过 TextBlock 来绑定键值对中的 Key。关键在于此处不是使用普通的 Binding而是使用了自定义的标记扩展 ResourceBinding其代码如下using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;namespace Mersoft.Mvvm.MarkupExtensions
{/// summary/// 用于处理 绑定代表资源键 (key) 的变量 业务的标记扩展类/// markup extension to allow binding to resourceKey in general case./// https://stackoverflow.com/questions/20564862/binding-to-resource-key-wpf/// /summary/// example/// code/// (Image Source{local:ResourceBinding ImageResourceKey}//// /code/// /examplepublic class ResourceBinding : MarkupExtension{#region Helper propertiespublic static object GetResourceBindingKeyHelper(DependencyObject obj){return (object)obj.GetValue(ResourceBindingKeyHelperProperty);}public static void SetResourceBindingKeyHelper(DependencyObject obj, object value){obj.SetValue(ResourceBindingKeyHelperProperty, value);}// Using a DependencyProperty as the backing store for ResourceBindingKeyHelper. This enables animation, styling, binding, etc...public static readonly DependencyProperty ResourceBindingKeyHelperProperty DependencyProperty.RegisterAttached(ResourceBindingKeyHelper, typeof(object), typeof(ResourceBinding), new PropertyMetadata(null, ResourceKeyChanged));static void ResourceKeyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e){var target d as FrameworkElement;var newVal e.NewValue as Tupleobject, DependencyPropertyif (target null || newVal null)return;var dp newVal.Item2;if (newVal.Item1 null){target.SetValue(dp, dp.GetMetadata(target).DefaultValue);return;}target.SetResourceReference(dp, newVal.Item1);}#endregionpublic ResourceBinding(){}public ResourceBinding(string path){Path new PropertyPath(path);}public override object ProvideValue(IServiceProvider serviceProvider){var provideValueTargetService (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget));if (provideValueTargetService null)return null;if (provideValueTargetService.TargetObject ! null provideValueTargetService.TargetObject.GetType().FullName System.Windows.SharedDp)return this;var targetObject provideValueTargetService.TargetObject as FrameworkElement;var targetProperty provideValueTargetService.TargetProperty as DependencyProperty;if (targetObject null || targetProperty null)return null;#region bindingBinding binding new Binding{Path Path,XPath XPath,Mode Mode,UpdateSourceTrigger UpdateSourceTrigger,Converter Converter,ConverterParameter ConverterParameter,ConverterCulture ConverterCulture,FallbackValue FallbackValue};if (RelativeSource ! null)binding.RelativeSource RelativeSource;if (ElementName ! null)binding.ElementName ElementName;if (Source ! null)binding.Source Source;#endregionvar multiBinding new MultiBinding{Converter HelperConverter.Current,ConverterParameter targetProperty};multiBinding.Bindings.Add(binding);multiBinding.NotifyOnSourceUpdated true;targetObject.SetBinding(ResourceBindingKeyHelperProperty, multiBinding);return null;}#region Binding Members/// summary/// The source path (for CLR bindings)./// /summarypublic object Source { get; set; }/// summary/// The source path (for CLR bindings)./// /summarypublic PropertyPath Path { get; set; }/// summary/// The XPath path (for XML bindings)./// /summary[DefaultValue(null)]public string XPath { get; set; }/// summary/// Binding mode/// /summary[DefaultValue(BindingMode.Default)]public BindingMode Mode { get; set; }/// summary/// Update type/// /summary[DefaultValue(UpdateSourceTrigger.Default)]public UpdateSourceTrigger UpdateSourceTrigger { get; set; }/// summary/// The Converter to apply/// /summary[DefaultValue(null)]public IValueConverter Converter { get; set; }/// summary/// The parameter to pass to converter./// /summary/// value/value[DefaultValue(null)]public object ConverterParameter { get; set; }/// summary/// Culture in which to evaluate the converter/// /summary[DefaultValue(null)][TypeConverter(typeof(System.Windows.CultureInfoIetfLanguageTagConverter))]public CultureInfo ConverterCulture { get; set; }/// summary/// Description of the object to use as the source, relative to the target element./// /summary[DefaultValue(null)]public RelativeSource RelativeSource { get; set; }/// summary/// Name of the element to use as the source/// /summary[DefaultValue(null)]public string ElementName { get; set; }#endregion#region BindingBase Members/// summary/// Value to use when source cannot provide a value/// /summary/// remarks/// Initialized to DependencyProperty.UnsetValue; if FallbackValue is not set, BindingExpression/// will return target propertys default when Binding cannot get a real value./// /remarkspublic object FallbackValue { get; set; }#endregion#region Nested typesprivate class HelperConverter : IMultiValueConverter{public static readonly HelperConverter Current new HelperConverter();public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture){return Tuple.Create(values[0], (DependencyProperty)parameter);}public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture){throw new NotImplementedException();}}#endregion}
}主要就是继承 MarkupExtension 并重写 ProvideValue 方法具体的本人也没怎么研究就先不说了大家感兴趣可以自己查一查。这里直接拿来使用可以达到动态绑定资源 key 的目的。 如果使用的是普通的 Binding则只能显示原始值 最后来看看中英文切换当然如果有其它语言也是一样可以切换的。首先是移除现有语言资源的方法/// summary
/// 语言名称列表
/// /summary
private readonly Liststring _LangKeys new Liststring() { en-us, zh-cn };/// summary
/// 移除语言资源
/// /summary
/// param nameremoveKeyList 需要移除的资源中包含的 key 的列表默认为空为空移除所有的 /param
private void RemoveLangThemes(Liststring removeKeyList null)
{if (removeKeyList null){removeKeyList _LangKeys;}var rd Application.Current.Resources;ListResourceDictionary removeList new ListResourceDictionary();foreach (var dictionary in rd.MergedDictionaries){// 判断是否是对应的语言资源文件bool isExists removeKeyList.Exists(x dictionary.Contains(LangName) dictionary[LangName] x);if (isExists){removeList.Add(dictionary);}}foreach (var removeResource in removeList){rd.MergedDictionaries.Remove(removeResource);}
}主要是对 Application.Current.Resources.MergedDictionaries 进行操作移除有 LangName 键且值为对应语言代号的资源字典。 然后是应用对应语言资源的方法及调用/// summary
/// 应用语言
/// /summary
/// param namepackUriTemplate 资源路径模板形如/WPFPractice;component/Resources/Language/{0}.xaml/param
/// param namelangName 语言名称形如zh-cn/param
private void ApplyLanguage(string packUriTemplate, string langName zh-cn)
{var rd Application.Current.Resources;//RemoveLangThemes();var packUri string.Format(packUriTemplate, langName);RemoveLangThemes(new Liststring() { langName });// 将资源加载在最后优先使用rd.MergedDictionaries.Add((ResourceDictionary)Application.LoadComponent(new Uri(packUri, UriKind.Relative)));
}/// summary
/// 语言资源路径模板字符串
/// /summary
private string _LangResourceUriTemplate /WPFPractice;component/Resources/Language/{0}.xaml;/// summary
/// 命令方法赋值在构造方法中调用
/// /summary
private void SetCommandMethod()
{SwitchCnCmd ?? new RelayCommand(o true, async o {ApplyLanguage(_LangResourceUriTemplate, zh-cn);});SwitchEnCmd ?? new RelayCommand(o true, async o {ApplyLanguage(_LangResourceUriTemplate, en-us);});
}逻辑就是先移除要切换到的语言资源的已存在的实例然后将新的实例放在最后以达到比其它语言资源如果有的话更高优先级的目的。 源码地址https://gitee.com/dlgcy/Practice/tree/Blog20210823发行版地址https://gitee.com/dlgcy/Practice/releases/Blog20210823 WPF【翻译】WPF 中附加行为的介绍 Introduction to Attached Behaviors in WPFWPF 使用 Expression Design 画图导出及使用 Path 画图WPF MVVM 弹框之等待框解决 WPF 绑定集合后数据变动界面却不更新的问题使用 ObservableCollectionWPF 消息框 TextBox 绑定新数据时让光标和滚动条跳到最下面真・WPF 按钮拖动和调整大小WPF MVVM 模式下的弹窗WPF 让一组 Button 实现 RadioButton 的当前样式效果WPF 原生绑定和命令功能使用指南WPF 用户控件的自定义依赖属性在 MVVM 模式下的使用备忘在WPF的MVVM模式中使用OCX组件
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/88476.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!