在下面的代碼示例,但是,您可以從德國將滑塊移動到英文,看到文本塊會轉換在運行時:爲什麼WPF綁定更新字符串而不是對象?
- 只綁定到串 TextBlock的被更新
- 的TextBlock的綁定到詞典不得到更新
看來,簡單地查看得到迪ctionary對象一旦,然後不再更新。我試過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的文章(http://www.codeproject.com/KB/WPF/WPFLocalize.aspx),它展示了一個在運行時改變資源文件語言的好方法。 – 2009-06-17 10:06:58