简介:这是我在应用程序中使用的翻译器的一部分。当我用组合框更改语言时,我想更新其中的所有字符串。
问题:我想在转换器属性更改时更新标签内容。有可能吗?如果我更改CurrentLanguage,这种方式(我是如何制作的(不会更新内容。
<Label
ID:Name="CompanyName"
Content="{Binding ElementName=CompanyName, Path=Name, Converter={ID:Static Controller:Translator.Instance}}" />
此组合框更改我的当前值-工作
<ComboBox
SelectedItem="{Binding Path=CurrentLanguage, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, Converter={StaticResource FlagConverter}}">
转换器代码背后-工作(PropertyChanged被解雇(
public partial class Translator : IValueConverter, INotifyPropertyChanged
{
...
private String m_currentLanguage;
public String CurrentLanguage
{
get { return m_currentLanguage; }
set
{
m_currentLanguage = value;
OnPropertyChanged("CurrentLanguage");
}
}
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return Get((String)value); // nonrelevant function - works
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return GetOriginal((String)value); // nonrelevant function - works
}
#region Events
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
我看到了两种可能的解决方案:
- 使用多值转换器并绑定到Name and CurrentLanguage
- 更像黑客:在comboxbox.itemchanged中添加一个事件触发器,并用Company.Name重置Company.NName的值(调用setter->调用converter(
解决方案:使用MultiBinding+IMultiValueConverter
组合框保持不变。
编辑Laber以使用MultiBinding。
<Label
ID:Name="CompanyName"
<Label.Content>
<MultiBinding Converter="{ID:Static Controller:Translator.Instance}">
<Binding ElementName="CompanyName" Path="Name"/>
<Binding Source="{ID:Static Controller:Translator.Instance}" Path="CurrentLanguage"/>
</MultiBinding>
</Label.Content>
</Label>
已将转换器更改为IMultiValueConverter:
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if ((values[0] as String).Length <= 0)
return ""; // prevents error messages for binds on element names
return Get((String)values[0]);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
太多人了!