繁体   English   中英

Windows Phone 7:将集合绑定到ListBox,以使Collection项中的更改在ListBox中更新

[英]Windows Phone 7: Binding a Collection to a ListBox such that a change in an Item of the Collection updates in the ListBox

抱歉,如果这是基本知识,但我找不到一个很好的示例来准确描述实现以下情况所需要做的工作:

我有两节课:

公共类Thing:DependencyObject {

    // Fields
    private string name = "";


    // Properties
    public string Name
    {
        get { return name; }
        set { name = value; }
    }


    // Dependency Properties

    public int Count
    {
        get { return (int)GetValue(CountProperty); }
        set { SetValue(CountProperty, value); }
    }

    public static readonly DependencyProperty CountProperty =
        DependencyProperty.Register("Count", typeof(int), typeof(Thing), null);


    // Methods
    public override string ToString()
    {
        return DateTime.Now.ToString() + " " + this.Name + " " + this.Count.ToString();

    }

    // Constructors

    public Thing(string name)
    {
        this.Name = name;
    }

}

和一个包含Thing对象的类

公共类的事情:DependencyObjectCollection {

}

MainPage.xaml.cs文件创建几个Thing对象,并将它们添加到Things集合中。

公共局部类MainPage:PhoneApplicationPage {Things Things = new Things();

    // Constructor
    public MainPage()
    {
        InitializeComponent();
        Thing thingA = new Thing("A");
        Thing thingB = new Thing("B");
        Things.Add(thingA);
        Things.Add(thingB);


    }

    private void Action_Click(object sender, RoutedEventArgs e)
    {
        this.Things[0].Count += 1;
        Debug.WriteLine(this.Things[0].ToString());
    }
}

我的问题是如何编写绑定代码,以使Thing对象的DependencyProperty Count更改时,ListBox可以显示事物对象中包含的事物,并且Thing对象作为ListBox中的字符串的显示会自动更新。

具体来说,我该如何执行以下XAML才能实现上述情况。
也就是说,当我将新的Thing对象添加到Things对象时,新项目将添加到ListBox。 当我使用Things对象更改现有项目时,更改将显示在ListBox中。

在Windows Phone 7中,MainPage包含一个ListBox:

    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <StackPanel>
            <ListBox x:Name="ThingsBox" />
            <Button x:Name="Action" Content="Action" Click="Action_Click"/>
        </StackPanel>
    </Grid>
</Grid>

如果您想以任何方式使用绑定,则应考虑遵循更多的MVVM模式,

即使没有它,您也可以绑定到对象。 您应该能够执行以下类似的操作

//code behind main page
Things ThingCollection { get; set }


//in xaml
<MainPage x:Name="_mainPage">

    <ListBox ItemsSource="{Binding ThingsCollection}" />
</MainPage>

这是一个简单的示例,但基本上是在xaml中要做的事情。

首先,我建议为模型使用普通的旧对象(实现INotifyPropertyChanged )。 依赖对象的使用是过大的。 请参阅以下相关问题:

ViewModel中的INotifyPropertyChanged与DependencyProperty

为了将您的对象集合绑定到列表,以使UI在添加/删除对象时自动更新,您应该创建一个ObservableCollection并将其设置为ListBoxItemsSource

ObservableCollection<Thing> ThingsCollection { get; set }

<MainPage x:Name="_mainPage">
    <ListBox ItemsSource="{Binding ThingsCollection}" />
</MainPage>

这里的关键是ObservableCollection实现INotifyCollectionChanged ,当更改集合时会引发事件。 ListBox处理这些事件,以使UI保持同步。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM