必要になった時に忘れているので覚書。
目的
XAML のあるアセンブリ(App.Forms)から別のアセンブリ(App.Shared)に定義した resx 形式で文字列リソースを参照したい。
構造としてはこう:
+ App.Shared
..+-- Resources
....+--Messages.resx
+ App.Forms
..+-- App.xaml
..+-- MainPage.xaml
手法
- 外部ライブラリ側のプロジェクトで、「ファイルの追加」ダイアログから Resx リソースを選び、Messages.resx を作成する。
- 修飾子を Public に変更する。 Xamarin Studio の場合はプロパティで「カスタムツール」の項目を「
PublicResXFileCodeGenerator
」に書き換える。 - 参照したい XAML ファイルのルート要素に名前空間とアセンブリ名を記述する。
- 利用先のプロパティで
x:Static
マークアップ拡張を使う。つまり、以下のようにする。
MainPage.xaml
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:resources="clr-namespace:App.Shared.Resources;assembly=App.Shared"
x:Class="App.Views.MainPage"
Title="MainPage">
<Label Text="{x:Static resources:Messages.Hello}"/>
</ContentPage>
国際化
国際化については Xamarin 公式のドキュメントに記述がある。
https://developer.xamarin.com/guides/xamarin-forms/advanced/localization/