第一步:把自己定义的资源写到app.xaml中去,如下所示:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Res/zh-cn.xaml"/> <!--这是你的资源文件-->
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
第二步:在ViewModel中调用:
var resource = Application.Current.Resources["resourceName"];
你可以使用强转类型进行转换得到你想要的类型,因为返回的是一个object类型
例: 我在资源文件中定义的是一个语言转换包,某个词语的转换的资源如下:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:system="clr-namespace:System;assembly=mscorlib">
<system:String x:Key="SwitchLanguage">切换语言</system:String>
</ResourceDictionary>
那么我在ViewModel中可以这么获取这个资源:
string getString= (string)Application.Current.Resources["SwitchLanguage"];
而得到的 getString的值就是我在资源文件中定义的 “切换语言” 的值。
参考:https://www.cnblogs.com/SherryWang/p/3297353.html