WPF MarkupExtension绑定错误

时间:2017-07-12 15:04:38

标签: wpf dependency-properties markup-extensions

implementing a multilanguage interface现在我遇到了问题。我有一个grid ItemSource它&#39; sa Dictionary<string, string>:我无法将键值作为标记扩展的参数,因为我有以下异常

A 'Binding' cannot be set on the 'Value1' property of type 'TranslateMarkupExtension'. 
A 'Binding' can only be set on a DependencyProperty of a DependencyObject.

这是我使用标记扩展名的xaml:

<ItemsControl ItemsSource="{Binding MyDictionary}" Grid.Row="0">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Grid Margin="10">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition></ColumnDefinition>
                        <ColumnDefinition></ColumnDefinition>
                    </Grid.ColumnDefinitions>
                    <Label Content="{TranslateMarkup Value1 = {Binding Path = Key}}" Grid.Column="0" /> 
                    <TextBox Tag="{Binding Key, Mode=OneWay}" Text="{Binding Value, Mode=OneWay}" Width="200" Height="46" VerticalContentAlignment="Center" Grid.Column="1" LostFocus="TextBox_OnLostFocus" />
                </Grid>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
</ItemsControl>

我无法找到任何解决方法..我需要将字典作为项目源,因为标签会显示键和文本框中的相应值。我也尝试用对象列表替换字典但是问题仍然存在。

有没有人有好的提示?提前谢谢。

1 个答案:

答案 0 :(得分:0)

根据Ed Plunkett的建议,解决方案ValueConverter

所以标签知道这个:

<Label Content="{Binding Key, Converter={StaticResource MultiLangConverter}}" Grid.Column="0" />

我的ValueConverter如下:

public class StringToMultiLangConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var stringValue = (string) value;
        if (string.IsNullOrEmpty(stringValue))
            return string.Empty;
        string multiLang = LangTranslator.GetString(stringValue);
        return multiLang ?? value;
    }


    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return DependencyProperty.UnsetValue;
    }
}

感谢您的帮助!