Compartilhar via


Visão geral de globalização e localização do WPF

When you limit your product's availability to only one language, you limit your potential customer base to a fraction of our world’s 6.5 billion population. If you want your applications to reach a global audience, cost-effective localization of your product is one of the best and most economical ways to reach more customers.

This overview introduces globalization and localization in Windows Presentation Foundation (WPF). Globalização é o design e desenvolvimento de aplicativos que executam em vários locais. Por exemplo, a globalização suporta dados regionais e interfaces de usuário localizada para usuários em diferentes culturas. WPFfornece recursos de design globalizado, inclusive layout automático, assemblies satélites e atributos localizados e a comentar.

Localization is the translation of application resources into localized versions for the specific cultures that the application supports. Quando você localizar em WPF, você usa as APIs na System.Windows.Markup.Localizer namespace. Alimentação essas APIs a Exemplo de ferramenta LocBaml ferramenta de linha de comando. For information about how to build and use LocBaml, see Como: Localizar um Aplicativo.

Este tópico contém as seguintes seções.

  • Best Practices for Globalization and Localization in WPF
  • Localize a WPF Application
  • Examples of WPF Localization

Best Practices for Globalization and Localization in WPF

You can make the most of the globalization and localization functionality that is built into WPF by following the UI design and localization-related tips that this section provides.

Best Practices for WPF UI Design

When you design a WPF–based UI, consider implementing these best practices:

  • Write your UI in XAML; avoid creating UI in code. Quando você cria seu UI usando XAML, ser exposto por meio de localização interna APIs.

  • Avoid using absolute positions and fixed sizes to lay out content; instead, use relative or automatic sizing.

    • Use SizeToContent; and keep widths and heights set to Auto.

    • Avoid using Canvas to lay out UIs.

    • Use Grid and its size-sharing feature.

  • Provide extra space in margins because localized text often requires more space. Extra space allows for possible overhanging characters.

  • Enable TextWrapping on TextBlock to avoid clipping.

  • Set the xml:lang attribute. This attribute describes the culture of a specific element and its child elements. O valor dessa propriedade altera o comportamento de vários recursos do WPF. Por exemplo, ele altera o comportamento de hifenização, verificação ortográfica, substituição de número, shaping de script complexo e fonte fallback. See Globalização para WPF for more information about setting the Manipulando xml:lang em XAML.

  • Create a customized composite font to obtain better control of fonts that are used for different languages. Por padrão, WPF usa a fonte de GlobalUserInterface.composite no seu Windows\Fonts diretório.

  • When you create navigation applications that may be localized in a culture that presents text in a right-to-left format, explicitly set the FlowDirection of every page to ensure the page does not inherit FlowDirection from the NavigationWindow.

  • When you create stand-alone navigation applications that are hosted outside a browser, set the StartupUri for your initial application to a NavigationWindow instead of to a page (for example, <Application StartupUri="NavigationWindow.xaml">). This design enables you to change the FlowDirection of the Window and the navigation bar. Para obter mais informações e um exemplo, consulte Exemplo de home page de globalização.

Best Practices for WPF Localization

When you localize WPF–based applications, consider implementing these best practices:

  • Use localization comments to provide extra context for localizers.

  • Use localization attributes to control localization instead of selectively omitting Uid properties on elements. See Localization Attributes and Comments for more information.

  • Use msbuild /t:updateuid and /t:checkuid to add and check Uid properties in your XAML. Use Uid Propriedades para controlar as alterações entre o desenvolvimento e a localização. Uid Propriedades ajudam você a localizar novas alterações de desenvolvimento. Se você adicionar manualmente Uid Propriedades para um UI, a tarefa é normalmente tedioso e menos precisas.

    • Do not edit or change Uid properties after you begin localization.

    • Do not use duplicate Uid properties (remember this tip when you use the copy-and-paste command).

    • Set the UltimateResourceFallback location in AssemblyInfo.* to specify the appropriate language for fallback (for example, [assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]).

      If you decide to include your source language in the main assembly by omitting the <UICulture> tag in your project file, set the UltimateResourceFallback location as the main assembly instead of the satellite (for example, [assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.MainAssembly)]).

Localize a WPF Application

When you localize a WPF application, you have several options. For example, you can bind the localizable resources in your application to an XML file, store localizable text in resx tables, or have your localizer use Extensible Application Markup Language (XAML) files. Esta seção descreve um fluxo de trabalho de localização que usa a forma BAML do XAML, que fornece vários benefícios:

  • You can localize after you build .

  • Você pode atualizar para uma versão mais recente do formulário BAML de localizações de XAMLwith de uma versão mais antiga do formulário BAML do XAML para que você pode localizar ao mesmo tempo em que você desenvolva.

  • Você pode validar os elementos de origem e a semântica original no momento da compilação porque o formulário BAML do XAML é a forma compilada da XAML.

Localization Build Process

When you develop a WPF application, the build process for localization is as follows:

  • The developer creates and globalizes the WPF application. Os conjuntos de desenvolvedor de arquivos no projeto <UICulture>en-US</UICulture> , de modo que quando o aplicativo é compilado, um assembly principal de idioma neutro é gerado. Este assembly tem um satélite. arquivo resources.dll que contém todos os recursos localizáveis. Opcionalmente, você pode manter o idioma de origem no assembly principal porque nossa localização APIs suporte a extração do assembly principal.

  • Quando o arquivo é compilado para a compilação, o XAML é convertido para o formulário BAML do XAML. Culturalmente neutro MyDialog.exe e culturalmente dependentes (em inglês) MyDialog.resources.dll arquivos são lançados para o cliente língua inglesa.

Localization Workflow

The localization process begins after the unlocalized MyDialog.resources.dll file is built. O UI elementos e propriedades no original XAML são extraídos do formulário BAML do XAML para pares de chave-valor usando o APIs em System.Windows.Markup.Localizer. Localizers use the key-value pairs to localize the application. You can generate a new .resource.dll from the new values after localization is complete.

As chaves dos pares chave-valor são x:Uid os valores que são colocados pelo desenvolvedor no original XAML. Essas x:Uid valores permitem que o API para controlar e mesclar as alterações que ocorrem entre o desenvolvedor e o localizador durante localização. Por exemplo, se o desenvolvedor altera o UI após o localizador começa localizando, você pode mesclar a alteração de desenvolvimento com o trabalho já concluído de localização para que o trabalho de tradução mínimo seja perdido.

O gráfico a seguir mostra um fluxo de trabalho de localização típico baseia-se no formulário BAML do XAML. This diagram assumes the developer writes the application in English. The developer creates and globalizes the WPF application. Os conjuntos de desenvolvedor de arquivos no projeto <UICulture>en-US</UICulture> , de forma que na compilação, um assembly principal neutra de idioma será gerado com um satélite. resources.dll que contém todos os recursos localizáveis. Alternately, one could keep the source language in the main assembly because WPF localization APIs support extraction from the main assembly. After the build process, the XAML get compiled into BAML. The culturally neutral MyDialog.exe.resources.dll get shipped to the English speaking customer.

Fluxo de trabalho de localizaçãoFluxo de trabalho não localizado

Examples of WPF Localization

This section contains examples of localized applications to help you understand how to build and localize WPF applications.

Run Dialog Box Example

The following graphics show the output of the Run dialog box sample.

English:

Caixa de diálogo Executar

German:

Caixa de diálogo Executar em alemão

Designing a Global Run Dialog Box

This example produces a Run dialog box by using WPF and XAML. This dialog box is equivalent to the Run dialog box that is available from the Microsoft Windows Start menu.

Some highlights for making global dialog boxes are:

Automatic Layout

In Window1.xaml:

<Window SizeToContent="WidthAndHeight">

The previous Window property automatically resizes the window according to the size of the content. This property prevents the window from cutting off content that increases in size after localization; it also removes unneeded space when content decreases in size after localization.

<Grid x:Uid="Grid_1">

Uid properties are needed in order for WPF localization APIs to work correctly.

Eles são usados por WPF localização APIs para controlar as alterações entre o desenvolvimento e a localização da user interface (UI). Uidpropriedades permitem que você mesclar uma versão mais recente do UI com uma localização mais antiga da UI. Você pode adicionar um Uid propriedade executando msbuild /t:updateuid RunDialog.csproj em um shell de comando. Este é o método recomendado de adicionar Uid propriedades como adicioná-los manualmente é geralmente demorada e menos precisas. You can check that Uid properties are correctly set by running msbuild /t:checkuid RunDialog.csproj.

O UI está estruturado, usando o Grid controle, que é um controle útil para aproveitar o layout automático no WPF. Note that the dialog box is split into three rows and five columns. Não, uma das definições de linha e coluna tem um tamanho fixo; Portanto, o UI os elementos são posicionados em cada célula podem se adaptar a aumenta e diminui de tamanho durante localização.

<Grid.ColumnDefinitions>
  <ColumnDefinition x:Uid="ColumnDefinition_1" />
  <ColumnDefinition x:Uid="ColumnDefinition_2" />

As duas primeiras colunas onde o Open: rótulo e ComboBox são colocados usar 10 por cento da UI largura total.

  <ColumnDefinition x:Uid="ColumnDefinition_3" SharedSizeGroup="Buttons" />
  <ColumnDefinition x:Uid="ColumnDefinition_4" SharedSizeGroup="Buttons" />
  <ColumnDefinition x:Uid="ColumnDefinition_5" SharedSizeGroup="Buttons" />
</Grid.ColumnDefinitions>

Note that of the example uses the shared-sizing feature of Grid. The last three columns take advantage of this by placing themselves in the same SharedSizeGroup. As one would expect from the name of the property, this allows the columns to share the same size. Então, quando "Procurar …" Obtém localizadas para seqüência mais longa "durchsuchen…", todos os botões crescem em largura, em vez de ter um pequeno "OK" botão e "Durchsuchen…" desproporcionalmente grande botão.

Xml:lang

Xml:lang="en-US"

Notice the Manipulando xml:lang em XAML placed at the root element of the UI. This property describes the culture of a given element and its children. This value is used by several features in WPF and should be changed appropriately during localization. This value changes what language dictionary is use to hyphenate and spell check words. It also affects the display of digits and how the font fallback system selects which font to use. Finally, the property affects the way numbers are displayed and the way texts written in complex scripts are shaped. O valor padrão é "en-US".

Building a Satellite Resource Assembly

In .csproj:

<UICulture>en-US</UICulture>

Observe a adição de um UICulture valor. When this is set to a valid CultureInfo value such as en-US, building the project will generate a satellite assembly with all localizable resources in it.

<Resource Include="RunIcon.JPG">

<Localizable>False</Localizable>

</Resource>

O RunIcon.JPG não precisam ser localizadas porque ela deve aparecer o mesmo para todas as culturas. Localizableé definido como false para que ela permaneça no idioma neutro assembly principal em vez do assembly satélite. O valor padrão de todos os recursos de noncompilable é Localizable definido como true.

Localizing the Run Dialog

Parse

After building the application, the first step in localizing it is parsing the localizable resources out of the satellite assembly. Para fins deste tópico, use a ferramenta de LocBaml de exemplo que pode ser encontrada em Exemplo de ferramenta LocBaml. Note that LocBaml is only a sample tool meant to help you get started in building a localization tool that fits into your localization process. Usando LocBaml, execute o seguinte para analisar: **LocBaml /parse RunDialog.resources.dll /out:**para gerar um "RunDialog.resources.dll.CSV" arquivo.

Localize

Use your favorite CSV editor that supports Unicode to edit this file. Filtre todas as entradas com uma categoria de localização de "None". You should see the following entries:

Resource Key

Localization Category

Value

Button_1:System.Windows.Controls.Button.$Content

Button

OK

Button_2:System.Windows.Controls.Button.$Content

Button

Cancel

Button_3:System.Windows.Controls.Button.$Content

Button

Browse...

ComboBox_1:System.Windows.Controls.ComboBox.$Content

ComboBox

TextBlock_1:System.Windows.Controls.TextBlock.$Content

Text

Type the name of a program, folder, document, or Internet resource, and Windows will open it for you.

TextBlock_2:System.Windows.Controls.TextBlock.$Content

Text

Open:

Window_1:System.Windows.Window.Title

Title

Run

Localizing the application to German would require the following translations:

Resource Key

Localization Category

Value

Button_1:System.Windows.Controls.Button.$Content

Button

OK

Button_2:System.Windows.Controls.Button.$Content

Button

Abbrechen

Button_3:System.Windows.Controls.Button.$Content

Button

Durchsuchen…

ComboBox_1:System.Windows.Controls.ComboBox.$Content

ComboBox

TextBlock_1:System.Windows.Controls.TextBlock.$Content

Text

Geben Sie den Namen eines Programms, Ordners, Dokuments oder einer Internetresource an.

TextBlock_2:System.Windows.Controls.TextBlock.$Content

Text

Öffnen:

Window_1:System.Windows.Window.Title

Title

Run

Generate

The last step of localization involves creating the newly localized satellite assembly. This can be accomplished with the following LocBaml command:

LocBaml.exe /generate RunDialog.resources.dll /trans:RunDialog.resources.dll.CSV /out: . /cul:de-DE

On German Windows, if this resources.dll is placed in a de-DE folder next to the main assembly, this resource will automatically load instead of the one in the en-US folder. Se você não tiver uma versão em alemão Windows para testar isso, defina a cultura para qualquer cultura dos Windows você estiver usando (ou seja, en-US) e substituir o original resources.dll.

Satellite Resource Loading

MyDialog.exe

en-US\MyDialog.resources.dll

de-DE\MyDialog.resources.dll

Code

Original English BAML

Localized BAML

Culturally neutral resources

Other resources in English

Other resources localized to German

A.NET framework escolhe automaticamente qual conjunto de recursos satélite carregar com base no aplicativo de Thread.CurrentThread.CurrentUICulture. This defaults to the culture of your Windows OS. So if you are using German Windows, the de-DE\MyDialog.resources.dll loads, if you are using English Windows, the en-US\MyDialog.resources.dll loads. You can set the ultimate fallback resource for your application by specifying the NeutralResourcesLanguage in your project’s AssemblyInfo.*. For example if you specify:

[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]

then the en-US\MyDialog.resources.dll will be used with German Windows if a de-DE\MyDialog.resources.dll or de\MyDialog.resources.dll are both unavailable.

Microsoft Saudi Arabia Homepage

The following graphics show an English and Arabic Homepage. Para obter o exemplo completo que produz esses elementos gráficos, consulte Exemplo de home page de globalização.

English:

Página em inglês

Arabic:

Página árabe

Designing a Global Microsoft Homepage

This mock up of the Microsoft Saudi Arabia web site illustrates the globalization features provided for RightToLeft languages. Languages such as Hebrew and Arabic have a right-to-left reading order so the layout of UI must often be laid out quite differently than it would be in left-to-right languages such as English. Localização de um idioma da esquerda para a direita para um idioma da direita para esquerda ou vice-versa pode ser bastante desafiador. WPFfoi projetado para facilitar a tais localizações.

FlowDirection

Homepage.xaml:

<Page x:Uid="Page_1" x:Class="MicrosoftSaudiArabiaHomepage.Homepage"
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"   
    FlowDirection="LeftToRight" 
    Localization.Comments="FlowDirection(This FlowDirection controls the actual content of the homepage)"
    xml:lang="en-US">

Observe o FlowDirection propriedade em Page. A alteração dessa propriedade para RightToLeft irá alterar o FlowDirection da Page e seus elementos filhos para que o layout deste UI é invertida para tornar-se da direita para a esquerda, como um usuário árabe esperaria. One can override the inheritance behavior by specifying an explicit FlowDirection on any element. O FlowDirection propriedade está disponível em qualquer FrameworkElement ou relacionado do elemento do documento e possui um valor implícito de LeftToRight.

Observe que mesmo os pincéis de gradiente do plano de fundo são invertidos corretamente quando a raiz FlowDirection é alterado:

FlowDirection="LeftToRight"

Fluxo da esquerda para a direita

FlowDirection="RightToLeft"

Fluxo da direita para a esquerda

Avoid Using Fixed Dimensions for Panels and Controls

Take a look through Homepage.xaml, notice that aside from the fixed width and height specified for the entire UI on the top DockPanel, there are no other fixed dimensions. Evite usar dimensões fixas para impedir que o recorte de texto localizado que pode ser maior do que o texto de origem. WPFos controles serão automaticamente com base no conteúdo que eles contêm de redimensionamento e painéis. A maioria dos controles também têm dimensões mínimas e máximas que podem ser definidas para ter mais controle (ou seja MinWidth = "20"). Com Grid, você também pode definir relativas larguras e alturas usando ' *' (ou seja, Largura = "0.25*") ou usar o seu tamanho de célula, recurso de compartilhamento.

Localization Comments

There are many cases where content may be ambiguous and difficult to translate. The developer or designer has the ability to provide extra context and comments to localizers through localization comments. For example the Localization.Comments below clarifies the usage of the character ‘|’.

<TextBlock 
  x:Uid="TextBlock_2" 
  DockPanel.Dock="Right" 
  Foreground="White" 
  Margin="5,0,5,0"
  Localization.Comments="$Content(This character is used as a decorative rule.)">
  |
</TextBlock>

This comment becomes associated with TextBlock_1’s content and in the case of the LocBaml Tool, ( see Como: Localizar um Aplicativo), it can be seen in the 6th column of the TextBlock_1 row in the output .csv file:

Resource Key

Category

Readable

Modifiable

Comment

Value

TextBlock_1:System.Windows.Controls.TextBlock.$Content

Text

TRUE

TRUE

This character is used as a decorative rule.

|

Comments can be placed on the content or property of any element using the following syntax:

<TextBlock 
  x:Uid="TextBlock_1" 
  DockPanel.Dock="Right" 
  Foreground="White" 
  Margin="5,0,5,0"
  Localization.Comments="$Content(This is a comment on the TextBlock's content.)
     Margin(This is a comment on the TextBlock's Margin property.)">
  |
 </TextBlock>

Localization Attributes

Often the developer or localization manager needs control of what localizers can read and modify. Por exemplo, você talvez não queira o localizador para traduzir o nome da sua empresa ou enunciado legal. WPFFornece atributos que permitem que você defina a legibilidade, modifiability e categoria de conteúdo ou propriedade que a ferramenta de localização pode usar para bloquear, ocultar ou classificar os elementos de um elemento. For more information, see Attributes. Para os fins deste exemplo, a ferramenta LocBaml saídas de apenas os valores desses atributos. WPFtodos os controles de tem valores padrão para esses atributos, mas você o pode substituí-los. Por exemplo, o exemplo a seguir substitui os atributos de localização padrão para TextBlock_1 e define o conteúdo esteja legível, mas unmodifiable para os localizadores.

<TextBlock
x:Uid="TextBlock_1"
Localization.Attributes=
"$Content(Readable Unmodifiable)">
  Microsoft Corporation
</TextBlock>

Juntamente com a legibilidade e atributos modifiability, WPF fornece uma enumeração das categorias comuns da interface do usuário (LocalizationCategory) que pode ser usado para os localizadores de dar mais contexto. The WPF default categories for platform controls can be overridden in XAML as well:

<TextBlock x:Uid="TextBlock_2">
<TextBlock.ToolTip>
<TextBlock
x:Uid="TextBlock_3"
Localization.Attributes=
"$Content(ToolTip Readable Unmodifiable)">
Microsoft Corporation
</TextBlock>
</TextBlock.ToolTip>
Windows Vista
</TextBlock>

The default localization attributes that WPF provides can also be overridden through code, so you can correctly set the right default values for custom controls. For example:

[Localizability(Readability = Readability.Readable, Modifiability=Modifiability.Unmodifiable, LocalizationCategory.None)]

public class CorporateLogo: TextBlock

{

..

.

}

The per instance attributes set in XAML will take precedence over the values set in code on custom controls. For more information on attributes and comments, see Localization Attributes and Comments.

Font Fallback and Composite Fonts

If you specify a font that does not support a given codepoint range, WPF will automatically fallback to one that does by using the Global User Interface.compositefont that is located in your Windows\Fonts directory. Fontes compostas funcionam exatamente como qualquer outra fonte e podem ser usadas explicitamente definindo (isto é, FontFamily um elemento FontFamily = "Interface de usuário Global"). You can specify your own font fallback preference by creating your own composite font and specifying what font to use for specific codepoint ranges and languages.

For more information on composite fonts see FontFamily.

Localizing the Microsoft Homepage

You can follow the same steps as the Run Dialog example to localize this application. O arquivo. csv de localizadas para árabe está disponível na Exemplo de home page de globalização.