【发布时间】:2014-08-21 23:47:02
【问题描述】:
我正在使用动态资源字典来翻译我的 GUI 元素。 字典在启动时加载,或者可以在运行时更改。 效果很好!
现在我必须以编程方式添加一些 GUI 元素.. 但是更改翻译后他们不会更新..
这是我如何“翻译”XAML 中的 GUI 元素:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:tests.Dialogs" x:Class="tests.Dialogs.Dlg_Main"
xmlns:Translator="clr-namespace:tests.Translation"
Title="{DynamicResource DLG_MAIN_TITLE}"
Height="356" Width="711"
/>
这是我添加到 ListBox 中的 MenuItem 类:
public class MenuItem : FrameworkElement
{
public MenuItem (string resourceKey, ClickAction action)
{
Action=action;
this.SetResourceReference(ContentProperty, resourceKey);
}
public void DoAction ()
{
if (Action!=null)
{
Action();
}
}
public delegate void ClickAction ();
private ClickAction Action;
public Object Content
{
get { return (Object)GetValue(ContentProperty); }
set { SetValue(ContentProperty, value); }
}
// Using a DependencyProperty as the backing store for Name. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ContentProperty=DependencyProperty.Register("Content", typeof(Object), typeof(MenuItem), new PropertyMetadata("leer?"));
}
这是 ListBox 的 XAML 样式:
<SolidColorBrush x:Key="ItemBrush" Color="Transparent" />
<SolidColorBrush x:Key="SelectedItemBrush" Color="Orange" />
<Style x:Key="RoundedItem" TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border Name="ItemBorder" BorderBrush="Transparent" BorderThickness="8,0,0,0" Margin="0" Padding="5" Background="{StaticResource ItemBrush}">
<StackPanel Orientation="Horizontal">
<TextBlock Margin="10,0,0,0" Text="{Binding Content.Content, RelativeSource={RelativeSource TemplatedParent}}" FontSize="18" FontWeight="Normal" VerticalAlignment="Center" />
</StackPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
ListBox 在 XAML 中这样使用:
<ListBox
x:Name="gui_listbox_menu"
ItemContainerStyle="{StaticResource RoundedItem}"
Background="Transparent"
SelectionChanged="gui_listbox_menu_SelectionChanged"
Margin="0,20,0,0"
ItemsSource="{Binding MenuItems, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:Dlg_Main}}}"
/>
启动后,MenuItems 有正确的翻译,所以参考有效?! 但如果我在运行时更改语言,只有 MenuItems 仍显示旧语言!
如果我以编程方式添加一个 Button 并将其 ReferenceSource 设置为 DynamicResource 其内容也会在运行时发生变化!
Button btn_test=new Button();
btn_test.Content="test";
btn_test.Width=100;
btn_test.Height=100;
gui_tab_settings_grid.Children.Add(btn_test);
btn_test.SetResourceReference(Button.ContentProperty, "DLG_MAIN_TITLE");
但我的 MenuItems 在运行时不会改变??!
欢迎任何帮助!
【问题讨论】:
-
也许你的
MenuItems 不工作正如你所说的那样,因为你试图在你的Resources之前从构造函数调用SetResourceReference方法已加载。稍后尝试调用它,看看会发生什么。 -
资源之前加载过!启动后会显示正确加载的翻译!!但如果我在运行时更改翻译,只有 MenuItem 不会改变并保持“最后一种语言”..
-
@pushpraj,问题作者已经说过我已经读过MarkUpExtensions不能以编程方式添加。
标签: c# wpf xaml translation markup-extensions