适用于名称值对的数据类型

时间:2013-02-27 09:14:56

标签: wpf data-binding

我想在我的班级中存储名称值对。我尝试了以下内容并最终得到以下问题;

  1. 使用NameValeCollection:这不成功。因为我想将此集合绑定到DataTemplate ItemsSource。我成功地绑定了名称,但没有成功收集集合中的
  2. 模板和XAML

     <DataTemplate x:Key="MyCollectionTemplate">
        <Grid>
            <TextBlock Text="{Binding Mode=OneWay}"/>
            <TextBox Name="CValue" Text="{Binding Path=Value}"/> //did not work this binding
        </Grid>
     </DataTemplate>     
    
     <ItemsControl ItemsSource="{Binding MyCollection}"  x:Name="MyCollectionControl" ItemTemplate="{DynamicResource MyCollectionTemplate}" />   
    

    MyCollectionNameValueCollection.

    1. 使用List<KeyValuePair<string,string>>:在这种情况下,我成功绑定了键值对。但不幸的是,它仅支持OneWay绑定。所以我也不能使用它。
    2. 请建议我处理这个问题的方法。我也不能使用Dictionary。因为在名称值对键中不是唯一的。

3 个答案:

答案 0 :(得分:2)

为什么不创建自己的自定义类?即。

public class MyClass
{
    public string Key { get; set; }
    public string Value { get; set; }
}

然后只有一个列表,或该类的可观察集合。

ObservableCollection<MyClass> MyCollection
{
    get;
    set;
}

请注意,如果您的馆藏值可能会发生变化,则需要在MyClass中实施INotifyProperyChanged。

答案 1 :(得分:1)

对于收藏,我建议使用ObservableCollection<T>

名称/值对听起来很简单,因此如果您想要对该对的名称和值进行更改通知,您可以实现具有这两个属性的类并自行更改通知(例如,通过INotifyPropertyChanged)并使用在你的收藏中。

您可以在此处找到有关如何在课堂上实施INotifyPropertyChanged的示例:
How to: Implement Property Change Notification

如果同时执行这两项操作,您将收到有关添加和删除名称/值对以及TwoWay绑定名称/值对的更改通知。

答案 2 :(得分:0)

您可以使用课程Tuple

喜欢

Tuple<string,string> t = Tuple.Create("key", "value");
string key = t.Item1;
string value = t.Item2;
相关问题