我开始在XAML中创建一个标签,其内容绑定到我的资源文件中的字符串。我已实施本地化并确认当我更改语言时,标签的内容会相应更新。
现在我需要从背后的代码中做同样的事情。
以下是XAML的味道:
<Grid Background="#FF313131">
<ScrollViewer>
<StackPanel x:Name="GeneralTab_StackPanel">
<WrapPanel VerticalAlignment="Top" Background="{Binding AxisDataColorCode}" Margin="2,2,2,0">
<Label x:Name="lbl_General_MachineType" Content="{Binding GUI_MachineType, Source={StaticResource Resources}}" FontSize="20" />
<Label x:Name="lbl_General_MachineTypeResult" Content="{Binding MachineBaseType}" FontSize="20" />
</WrapPanel>
<WrapPanel....
尝试在代码隐藏中重新创建此代码我有以下内容:
Binding BgColorBinding = new Binding("AxisDataColorCode");
// Something needs to change here. I've tried a bunch of things already with no luck.
Binding GUI_MachineTypeBinding = new Binding("GUI_MachineType");
GUI_MachineTypeBinding.Source = Properties.Resources.GUI_MachineType;
Binding MachineBaseTypeBinding = new Binding("MachineBaseType");
Label Label_MachineType = new Label();
Label_MachineType.Name = "lbl_General_MachineType";
Label_MachineType.FontSize = 20;
// This does not work at all. Help!
Label_MachineType.SetBinding(Label.ContentProperty, GUI_MachineTypeBinding);
// this works! but it's not a binding and doesn't update...
// Label_MachineType.Content = Properties.Resources.GUI_MachineType;
Label Label_MachineTypeResult = new Label();
Label_MachineTypeResult.Name = "lbl_General_MachineTypeResult";
Label_MachineTypeResult.FontSize = 20;
Label_MachineTypeResult.SetBinding(Label.ContentProperty, MachineBaseTypeBinding);
WrapPanel MachineTypeWrapPanel = new WrapPanel();
MachineTypeWrapPanel.Name = "MachineTypeWrapPanel";
MachineTypeWrapPanel.VerticalAlignment = System.Windows.VerticalAlignment.Top;
MachineTypeWrapPanel.Margin = new Thickness(2, 2, 2, 0);
MachineTypeWrapPanel.SetBinding(WrapPanel.BackgroundProperty, BgColorBinding);
MachineTypeWrapPanel.Children.Add(Label_MachineType);
MachineTypeWrapPanel.Children.Add(Label_MachineTypeResult);
我的其他绑定工作正常,因为我只是将它们绑定到实现属性更改通知后面的代码中的属性。
尝试绑定到我的资源中的任何键,但是没有给我任何东西。标签的内容只是空白,我的调试输出窗口中没有错误。
我无法找到任何人从任何地方的代码绑定到 Properties.Resources.Whatever 的任何示例。
解决方案:
感谢Henka!
Binding GUI_MachineTypeBinding = new Binding("GUI_MachineType");
GUI_MachineTypeBinding.Source = Application.Current.FindResource("Resources");
....
Label_MachineType.SetBinding(Label.ContentProperty, GUI_MachineTypeBinding);
答案 0 :(得分:2)
如果您从UI后面的代码设置Binding将不会收到通知,您应该创建自定义扩展并将WeakReference
保存到DependencyProperty
并在文化发生变化时更新值,我建议要使用的其他解决方案,请查看本文。Advanced WPF Localization