【问题标题】:Populating a ListBox (WPF) with an ObservableCollection使用 ObservableCollection 填充 ListBox (WPF)
【发布时间】:2013-06-11 17:21:38
【问题描述】:

我已经仔细阅读了此站点上的所有相关问题,但由于某种原因,我无法用两个 ObservableCollections 填充我的两个 ListBoxes。是我的绑定问题还是模型中的某个地方有问题?

型号:

public class DataModel : INotifyPropertyChanged
{
    public ObservableCollection<object> List1
    {
        get
        {
            return this.List1;
        }
        set
        {
            this.List1 = value;
            this.OnPropertyChanged("List1");
        }
    }

    public ObservableCollection<object> List2
    {
        get
        {
            return this.List2;
        }
        set
        {
            this.List2 = value;
            this.OnPropertyChanged("List2");
        }
    }

    public DataModel(ObservableCollection<object> _list1, ObservableCollection<object> _list2)
    {
        this.List1 = _list1;
        this.List2 = _list2;
    }

    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

XAML.cs:

public partial class UserControl1 : UserControl
{
    public ObservableCollection<object> l;
    public ObservableCollection<object> m;

    public UserControl1()
    {
        l = new ObservableCollection<object> { "test1a", "test1b" };
        m = new ObservableCollection<object> { "test2a", "test2b" };
        InitializeComponent();
        DataModel inst = new DataModel(l, m);
        this.DataContext = inst;
        this.TelProps.ItemsSource = l;
        this.SurProps.ItemsSource = m;
    }
}

XAML:

<Grid Name="Grid" DataContext="inst">
    <ListBox Name="FirstProps" 
             DataContext="{Binding Source=inst}"
             ItemsSource="{Binding List1}"
             DisplayMemberPath="List1" />
    <ListBox Name="SecondProps" 
             DataContext="{Binding Source=inst}"
             ItemsSource="{Binding List2}"
             DisplayMemberPath="List2" />
</Grid>

【问题讨论】:

  • 您的代码看起来不正确。尝试获取或设置属性 List1 或 List2 的值时,您将收到 StackOverflowException。您需要那里的支持字段。

标签: c# .net wpf data-binding listbox


【解决方案1】:

您需要删除 DisplayMemberPath 说明符。这就是说要在List1 的每个项目上查找List1 属性。由于List1 仅包含一组字符串,因此System.String 上没有List1 属性,因此会出现绑定错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多