-
Notifications
You must be signed in to change notification settings - Fork 14
Wpf Intro
The GetText.NET.Wpf package provides localization support for WPF elements. It can translate text properties in a window or another WPF element tree using the same ICatalog and gettext catalogs as the rest of GetText.NET.
Install the package with:
dotnet add package GetText.NET.Wpf
GetText.NET.Extractor parses .xaml files and exports literal values from common translatable attributes, including Content, Header, Label, Text, Title and ToolTip. It also extracts direct text from TextBlock, Run and AccessText elements.
For example:
<Window x:Class="Example.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Title="Hello, world!">
<StackPanel>
<TextBlock Text="Welcome" />
<Button Content="Continue" ToolTip="Continue to the next step" />
</StackPanel>
</Window>The extractor includes these literal values in the generated PO template. Markup extensions and data-bound properties are left for the application to resolve.
GetText.Wpf.Localizer walks the logical and visual trees below a DependencyObject and translates writable string properties. It handles Text, Title, Content, Header and ToolTip, as well as DataGridColumn and GridViewColumn headers.
using GetText;
using GetText.Wpf;
public partial class MainWindow : Window
{
private readonly ObjectPropertiesStore originalTextStore = new ObjectPropertiesStore();
private void SetTexts(ICatalog catalog)
{
GettextExtension.DefaultCatalog = catalog;
Localizer.Localize(this, catalog, originalTextStore);
}
private void RestoreOriginalTexts()
{
Localizer.Revert(this, originalTextStore);
}
}The localizer skips properties that are data-bound. Use ObjectPropertiesStore when the UI needs to switch languages repeatedly: call Localizer.Revert before loading the new catalog and calling Localizer.Localize again.
The WPF package also provides the Gettext markup extension for values that should be resolved directly by XAML:
<Window xmlns:gt="clr-namespace:GetText.Wpf;assembly=GetText.Wpf">
<TextBlock Text="{gt:Gettext Hello, world!}" />
</Window>Set GettextExtension.DefaultCatalog before the XAML value is evaluated, or use the extension with the catalog initialization pattern used by the application.