有没有办法为本地化扩展全局分配默认值?

时间:2015-09-16 14:52:33

标签: c# wpf

问题陈述是,我最终在我的所有视图中复制并粘贴了xaml行块。

lex:LocalizeDictionary.DesignCulture="en"
lex:ResxLocalizationProvider.DefaultAssembly="WPF.Common"
lex:ResxLocalizationProvider.DefaultDictionary="global"
xmlns:lex="http://wpflocalizeextension.codeplex.com">

是否有某种机制可以将此分配放在某个文件中并派生到所有视图中?

3 个答案:

答案 0 :(得分:1)

你可以使用附加行为,这里是非常简单的(哑)版本:

public class MyBevavior
{
    public static bool GetProperty(DependencyObject obj) => (bool)obj.GetValue(PropertyProperty);
    public static void SetProperty(DependencyObject obj, bool value) => obj.SetValue(PropertyProperty, value);

    public static readonly DependencyProperty PropertyProperty =
        DependencyProperty.RegisterAttached("Property", typeof(bool), typeof(Class), new PropertyMetadata(false, (d, e) =>
        {
            LocalizeDictionary.SetDesignCulture(d, "en");
            ResxLocalizationProvider.SetDefaultAssembly(d, "WPF.Common");
            ResxLocalizationProvider.SetDefaultDictionary(d, "global")
        }));
}

然后xaml变得更短

<Window local:MyBehavior.Property="true" ...>
...

注意,您可以使用一些有意义的参数进行配置。目前的形式是bool,这是愚蠢的,也许将en作为string传递是有意义的。

或者您可以为所有观看次数设置基本类型,例如MyWindow,您可以在构造函数中设置它们。

或者您可以将其移动到每个窗口的OnLoad事件中。

答案 1 :(得分:1)

为什么不使用资源字典中定义的样式?

<Style x:Key="ViewStyle">
   <Setter Property="lex:LocalizeDictionary.DesignCulture" Value="en" />
   <Setter Property="lex:ResxLocalizationProvider.DefaultAssembly" Value="WPF.Common" />
   <Setter Property="lex:ResxLocalizationProvider.DefaultDictionary" Value="global" />
</Style>

然后在视图中使用该样式:

<UserControl Style="{StaticResource ViewStyle}">
<Page Style="{StaticResource ViewStyle}">
<Window Style="{StaticResource ViewStyle}">
BTW,Visual Studio提供了一些很好的功能来简化这种例程。

例如,您可以创建custom Item Template来生成包含所需内容的视图。如果您愿意,模板还可以包含视图的ViewModel。创建自定义项模板非常容易。

同样,你可以创建custom code snippet,这甚至更简单。当您编写“lex”然后按Tab键时,它会为您生成内容。

答案 2 :(得分:0)

在应用程序资源中为UserControl类型创建默认样式。

XAML:

 <Application x:Class="WpfApplication1.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:lex="http://wpflocalizeextension.codeplex.com"
         StartupUri="MainWindow.xaml">
   <Application.Resources>
       <Style TargetType="UserControl">
           <Setter Property="lex:LocalizeDictionary.DesignCulture" Value="en" />
           <Setter Property="lex:ResxLocalizationProvider.DefaultAssembly" Value="WPF.Common" />
           <Setter Property="lex:ResxLocalizationProvider.DefaultDictionary" Value="global" />
       </Style>
    </Application.Resources>
</Application>
相关问题