第一步:把自己定義的資源寫到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