2015-09-16 33 views
0

问题陈述是,我最终在我所有的视图中复制并粘贴下面的xaml行块。有没有办法为本地化扩展程序全局分配默认值?

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

是否有一些机制可以将这个赋值放到某个文件中并在所有视图中派生?

+0

设置其他附加属性的附加行为。 – Sinatr

+0

谢谢@Sinatr的答案。但抱歉,我不明白你,我是WPF新手。你能举个例子或者更好的解释吗? –

回答

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> 
+0

隐式样式不适用于继承的类。例如,此样式不会应用于从UserControl继承的任何视图 – Liero

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

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

<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时,它会为你生成东西。

相关问题