动态更新列表框文本值

时间:2015-10-27 06:20:22

标签: c# windows-phone-8 listbox observablecollection

我找到了添加或删除列表框中利用Observable Collection的项目的方法。但我想更新列表框中的所有特定绑定属性值,例如,仅在列表框中更新所有文本块。这是在列表框中添加项目的示例,但我想更新值:绑定按钮上的名称单击列表框外部,那么我该如何实现呢?

public partial class MainPage : PhoneApplicationPage
{
    // Constructor
    public MainPage()
    {
        InitializeComponent();
        FillListBox();
    }
    MovieList Mov = new MovieList();
    private void FillListBox()
    {
        listBox1.ItemsSource = Mov;
        listBox1.DisplayMemberPath = "Name";
        listBox1.SelectionChanged += new SelectionChangedEventHandler(listBox1_SelectionChanged);
    }
    void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        Mov.Add(new Movie { Name = "Ghillli", Actor = "Vijay" });
    }
}
public class Movie
{
    public string Actor { get; set; }
    public string Name { get; set; }
}
public class MovieList : ObservableCollection
{
    public MovieList()
    {
        Add(new Movie { Name = "Kaavalan", Actor = "Vijay", });
        Add(new Movie { Name = "Velayutham", Actor = "Vijay", });
        Add(new Movie { Name = "7th Sense", Actor = "Surya", });
        Add(new Movie { Name = "Billa 2", Actor = "Ajith Kumar", });
        Add(new Movie { Name = "Nanban", Actor = "Vijay", });
    }
}

那么如何更新所有值绑定列表框中的Name属性而不使用nulling itemsource并重新绑定所有值并仅更新Name属性?

1 个答案:

答案 0 :(得分:1)

更改代码如下:

public class Movie
{
    public string Actor { get; set; }
    public string Name { get; set; }
}
public class MovieList : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        var mevent = PropertyChanged;
        if (mevent != null)
        {
            mevent(this, e);
        }
    }

    ObservableCollection<Movie> Movieitems = new ObservableCollection<Movie>();
    public ObservableCollection<Movie> MovieItems
    {
        get { return Movieitems; }
        set
        {
            if (Movieitems == value)
            {
                return;
            }
            Movieitems = value;
            OnPropertyChanged(new PropertyChangedEventArgs("MovieItems"));
        }
    }

    public MovieList()
    {
        Movieitems.Add(new Movie { Name = "Kaavalan", Actor = "Vijay", });
        Movieitems.Add(new Movie { Name = "Velayutham", Actor = "Vijay", });
        Movieitems.Add(new Movie { Name = "7th Sense", Actor = "Surya", });
        Movieitems.Add(new Movie { Name = "Billa 2", Actor = "Ajith Kumar", });
        Movieitems.Add(new Movie { Name = "Nanban", Actor = "Vijay", });
    }
}

item dynamically in listbox中添加listBox1_SelectionChanged,如下所示:

Mov.MovieItems.Add(new Movie { Name = "Ghillli", Actor = "Vijay" });

修改

用于更新现有的Name属性

Mov.MovieItems[SelectedIndexValue] = new Movie { Name = "Ghillli", Actor = "Vijay" };

SelectedIndexValue = 0,1,2,3 ......等。

对于集合的更新Name属性

Mov.MovieItems[SelectedIndexValue].Name = "Ghillli";