WPF(MVVM) 利用资源字典实现中英文动态切换

1、首先新建两个字典文件en-us.xaml、zh-cn.xaml。定义中英文的字符串在这里面。

2、将两个资源字典添加到App.xaml中,这里注意下,因为两个字典中有同样字符,如果没有动态更改,默认后添加的生效

    <ResourceDictionary  Source="/Resourcedictionaries\en-us.xaml"/>
    <ResourceDictionary  Source="/Resourcedictionaries\zh-cn.xaml"/>

3、 如何动态切换资源字典

 System.Windows.ResourceDictionary resource = new System.Windows.ResourceDictionary();//定义一个资源字典的类型
            string requestedCulture = @"/Resourcedictionaries\zh-cn.xaml";设置资源字典的路径
            resource.Source = new Uri(requestedCulture, UriKind.RelativeOrAbsolute);//将路劲存进资源字典
            Application.Current.Resources.MergedDictionaries.Remove(resource);删除相关字典
            Application.Current.Resources.MergedDictionaries.Add(resource);添加字典

4:如何调用资源字典的样式 前端我们一般DynamicResource +key

后台则是FindResource("资源字典的KEY")as string

但是在MVVM 模式下是得不到这个方法的 所以应该用到Application.Current.TryFindResource("资源字典的KEY) as string;这个方法来获取资源字典的内容

posted @ 2019-08-08 14:56  可乐_加冰  阅读(1736)  评论(0编辑  收藏  举报