UWP / XAML中字典的双向数据绑定

时间:2016-06-15 06:04:09

标签: c# xaml data-binding uwp

我目前有一个应用程序,我正在解析YAML字典。我有一个名为Line的模型,看起来像这样 -

    public class Line
    {

        private ObservableDictionary<string, string> language = new ObservableDictionary<string, string>();

        public Line()
        {
            Language = new Dictionary<string, string>();
        }

        // used with the YAML parser
        [YamlMember(Alias = "language")]
        public Dictionary<string, string> Language { get; set; }

    }

您可能已经注意到我使用的是ObservableDictionary,这不是标准类型。我从这个other StackOverflow answer获取了代码。据我了解,它只是设置必要的INotifyPropertyChanged界面。

无论如何,对于我的Line,我有ListView填充了作为语言缩写和文本框的翻译词典。为了更好地举例说明我所说的内容,这里有一个图形。

enter image description here

在我的App.xaml中,我为我的ListView定义了DataTemplate - 它们一起显示如下:

<ListView 
    ItemTemplate="{StaticResource LinesTemplateItem}" 
    ItemsSource="{Binding Value.Language}" 
    SelectionMode="None">
</ListView>

...

<DataTemplate x:Key="LinesTemplateItem">
    <StackPanel Background="Transparent">
        <TextBlock Text="{Binding Key}" />
        <TextBox Text="{Binding Value, Mode=TwoWay}" />
    </StackPanel>
</DataTemplate>

一切似乎都应该可以正常工作。我的数据显示正确。但是,当我更改值时,它不会使用错误更新基础源:

Error: Cannot save value from target back to source. 
BindingExpression: Path='Value' DataItem='Windows.Foundation.Collections.IKeyValuePair`2<String,String>'; 
target element is 'Windows.UI.Xaml.Controls.TextBox' (Name='null'); 
target property is 'Text' (type 'String').

从错误中,我猜想由于某种原因,数据绑定是针对整个UI控件而不是其中的文本。我一直在寻找,但我似乎无法弄清楚如何解决这个错误。任何帮助表示赞赏。感谢。

2 个答案:

答案 0 :(得分:2)

问题是属性IKeyValuePair.Value是只读的,因此您无法对其进行修改。我的主张是稍微改变你的数据模型,即首先创建一个额外的类来存储翻译。

public class Translation
{
   public string Expression { get; set; }
}

现在您还应该更改词典的定义,例如:

public Dictionary<string, Translation> Language { get; set; }

绑定也应相应更新:

<TextBox Text="{Binding Value.Expression, Mode=TwoWay}" />

多亏了这一点,如果更改了一个值,数据绑定将更新Expression属性,该属性不是只读的。

我没有测试过这段代码,但过去我做过类似的事情,所以这样的事情应该有效。

答案 1 :(得分:1)

由于您已绑定到Dictionary<string,string>,因此每个项目都绑定到KeyValuePair<string,string>,这是有价值的类型 - 它的字段无法更改(在取消装箱时)。您应该绑定到对本身,而不是它的部分,并使用值转换器来生成具有更改值的对。