【问题标题】:How to bind data to ListBox.ItemSource using MVVM pattern如何使用 MVVM 模式将数据绑定到 ListBox.ItemSsource
【发布时间】:2011-09-04 16:21:48
【问题描述】:

我是 WP7 应用程序的开发人员。 有谁知道如何在 ViewModel 类中将数据绑定到 ListBox.ItemSource 的想法?

【问题讨论】:

    标签: windows-phone-7 silverlight-4.0


    【解决方案1】:
    <ListBox ItemsSource={Binding ViewModelPropertyName}" />
    

    ViewModelPropertyName 应该返回 IList 或更好。
    如果要显示对集合的更改,它应该返回一个INotifyCollectionChanged,例如ObservableCollection&lt;T&gt;

    <ListBox ItemsSource={Binding ViewModelPropertyName}" />
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text={Binding PropertyNameWithinObject} />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    

    【讨论】:

    • 感谢您的回复。我找到了你写的一个样本。我会试试看。如果您知道,请告诉我好的样品。
    【解决方案2】:

    在上面的同一个例子中,你需要在类中定义绑定名称“ViewModelPropertyname”

    示例:类名称为“模型”

            int _PropertyNameWithinObject;
            public int PropertyNameWithinObject
            {
                get
                {
                    return PropertyNameWithinObject;
                }
                set
                {
                    PropertyNameWithinObject= value;
                    OnPropertyChanged("PropertyNameWithinObject");
                }
            }
    

    在“模型”类中包含以下类

    public class ViewModelBaseEx : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
            protected void OnPropertyChanged(string name)
            {
                PropertyChangedEventHandler handler = PropertyChanged;
                if (handler != null)
                {
                    handler(this, new PropertyChangedEventArgs(name));
                }
            }
        }
    

    然后在另一个名为“ViewModel”的整洁类中定义集合

            ObservableCollection<Model> _ViewModelPropertyName= new ObservableCollection<Model>();
            public ObservableCollection<Model> ViewModelPropertyName
            {
                get
                {
                    return _ViewModelPropertyName;
                }
                set
                {
                    _ViewModelPropertyName= value;
                    OnPropertyChanged("ViewModelPropertyName");
                }
            }
    

    对于以下绑定

     <ListBox ItemsSource={Binding ViewModelPropertyName}" />
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text={Binding PropertyNameWithinObject} />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    

    并在 c# 或设计中在此页面的 datacontext 中分配类“ViewModel”,这里我在 c# 页面中声明, 喜欢

    this.DataContext = ViewModel;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-11
      • 1970-01-01
      • 2011-04-03
      • 1970-01-01
      • 1970-01-01
      • 2013-12-03
      • 1970-01-01
      • 2015-05-15
      相关资源
      最近更新 更多