15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

596 ❘ ChaPTer 22 lOcAlizAtiOn<br />

be available to the complete application. Here, the resource dictionary is added within the resources of the<br />

main window:<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

code snippet WPFApplicationUsingXAMLDictionaries/MainWindow.xaml<br />

To use the XAML resource dictionary from code behind, you can use the indexer of the Resources<br />

property, the FindResource() method or the TryFindResource() method. Because the resource is<br />

defined with the window, the indexer of the Resources property of the Window class can be used to access<br />

the resource. FindResource() does a hierarchical search for a resource. If you use the FindResource()<br />

method of the Button, <strong>and</strong> if it is not found with the Button resources, then resources are searched in<br />

the Grid. If the resource is not there, a lookup to the Window resources is done before the Application<br />

resources are consulted.<br />

private void Button_Click(object sender, RoutedEventArgs e)<br />

{<br />

MessageBox.Show(this.Resources["Message1"] as string);<br />

MessageBox.Show(this.FindResource("Message1") as string);<br />

}<br />

code snippet WPFApplicationUsingXAMLDictionaries/MainWindow.xaml.cs<br />

Uid attributes for localization<br />

With the custom resource dictionary file, the text from the code that should be localized can be referenced.<br />

For localizing XAML code with WPF elements, the x:Uid attribute is used as a unique identifier for the<br />

elements that need localization. You don’t have to apply this attribute manually to the XAML content;<br />

instead, you can use the msbuild comm<strong>and</strong> with this option:<br />

msbuild /t:updateuid<br />

When you call this comm<strong>and</strong> in the directory where the project file is located, the XAML files of the project<br />

are modified to add an x:Uid attribute with a unique identifier to every element. If the control already has<br />

a Name or x:Name attribute applied, the x:Uid has the same value; otherwise, a new value is generated. The<br />

same XAML that was shown before now has the new attributes applied:<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!