【发布时间】:2009-06-17 09:32:07
【问题描述】:
在以下代码示例中,您可以将滑块从德语移动到英语,然后在运行时看到该文本块被翻译:
- 只有绑定到 字符串 的 TextBlock 才会更新
- 绑定到字典的 TextBlock 没有更新
View 似乎只是获取 Dictionary 对象一次,然后不再更新。我试过 Mode=TwoWay 但没有效果。
我必须做些什么才能使绑定到对象的元素通过绑定得到更新?
查看:
<Window x:Class="TestObjectUpdate234.Views.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:TestObjectUpdate234.Commands"
Title="Main Window" Height="400" Width="800">
<StackPanel Margin="10">
<TextBlock Text="{Binding TranslationEdit}" />
<TextBlock Text="{Binding Translations[add], Mode=TwoWay}" />
<StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal" Margin="0 20 0 0">
<TextBlock Text="English" Margin="0 0 5 0"/>
<Slider Name="TheLanguageIndexSlider"
Minimum="0"
Maximum="1"
IsSnapToTickEnabled="True"
Width="100"
Margin="5"
Value="{Binding LanguageIndex}"
HorizontalAlignment="Left"/>
<TextBlock Text="German" Margin="5 0 0 0"/>
</StackPanel>
</StackPanel>
</Window>
视图模型:
using System.Collections.Generic;
namespace TestObjectUpdate234.ViewModels
{
public class MainViewModel : ViewModelBase
{
#region ViewModelProperty: TranslationEdit
private string _translationEdit;
public string TranslationEdit
{
get
{
return _translationEdit;
}
set
{
_translationEdit = value;
OnPropertyChanged("TranslationEdit");
}
}
#endregion
#region ViewModelProperty: Translations
private Dictionary<string, string> _translations = new Dictionary<string, string>();
public Dictionary<string, string> Translations
{
get
{
return _translations;
}
set
{
_translations = value;
OnPropertyChanged("Translations");
}
}
#endregion
#region ViewModelProperty: LanguageIndex
private int _languageIndex;
public int LanguageIndex
{
get
{
return _languageIndex;
}
set
{
_languageIndex = value;
OnPropertyChanged("LanguageIndex");
FillTranslations();
}
}
#endregion
public MainViewModel()
{
_languageIndex = 0; //english
FillTranslations();
}
private void FillTranslations()
{
if (_languageIndex == 0)
{
TranslationEdit = "Edit";
Translations.Clear();
Translations.Add("add", "Add");
}
else
{
TranslationEdit = "Bearbeiten";
Translations.Clear();
Translations.Add("add", "Hinzufügen");
}
}
}
}
【问题讨论】:
-
值得指出的是,这不是 WPF 本地化的好策略。为本地化字符串使用资源比将它们存储在字典中更为常见和有用。有一篇关于 CodeProject (codeproject.com/KB/WPF/WPFLocalize.aspx) 的文章展示了一种在运行时更改资源文件语言的好方法。