如何在WPF中使用ObservableCollection绑定ItemsSource

5

在我的WPF应用程序中,我通过Button Click Event HandlerObservableCollection添加新项目。现在我想通过将Binding绑定到ItemsControl来立即显示这个添加的项目,但我的代码不起作用。有人能解决我的问题吗?以下是我的代码:

.XAML文件

    <dxlc:ScrollBox VerticalAlignment="Top">
        <ItemsControl x:Name="lstItemsClassM" ItemsSource="{Binding Path=topp,   Mode=TwoWay}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Vertical">
                        <Button Content="{Binding Name}"  Tag="{Binding PKId}"/>
                      </StackPanel>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

    </dxlc:ScrollBox>

.CS 文件

     public ObservableCollection<ClassMM> topp { get; set; }

    int dv , startindex, lastindex;

    public MainWindow()
    {

        InitializeComponent();
        topp = new ObservableCollection<ClassMM>();
        startindex=dv=1;
        topp.Add(new ClassMM() {  PKId=dv, Name = "Test 1" });
        dv=2;
        topp.Add(new ClassMM() { PKId = dv, Name = "Test 2" });
        dv = 3;
        topp.Add(new ClassMM() { PKId = dv, Name = "Test 3" });

        dv = 4;
        topp.Add(new ClassMM() { PKId = dv, Name = "Test 4" });

        lastindex=dv = 5;
        topp.Add(new ClassMM() { PKId = dv, Name = "Test 5" });


    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        lastindex = dv = dv++;

        topp.Add(new ClassMM() { PKId = dv, Name =  musavebutton.Content.ToString() });
        foreach (var jk in topp.ToList())
        {
            MessageBox.Show(jk.Name);
        }
    }
     public class ClassMM : INotifyPropertyChanged
{
    public string _name;
    public int _pkid;


    public int PKId
    {
        get { return _pkid; }
        set
        {
            if (value != _pkid)
            {
                _pkid = value;
                NotifyPropertyChanged();
            }
        }
    }



    public string Name
    {
        get { return _name; }
        set
        {
            if (value != _name)
            {
                _name = value;
                NotifyPropertyChanged();
            }
        }
    }



    public event PropertyChangedEventHandler PropertyChanged;

    protected void NotifyPropertyChanged(String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
     }
   }

}


1
我的猜测是你的MainWindow需要实现iNotifyPropertyChanged接口。但是HichemCSharp的回答中在set上使用NotifyPropertyChanged并不是必须的(但也不会有任何影响)。 - paparazzo
2个回答

3
保留原始的XAML,然后按照以下方式修改你的 cs 文件:
 public ObservableCollection<ClassMM> topp { get; set; }

        private int dv, startindex, lastindex;

        public MainWindow()
        {

            InitializeComponent();
            DataContext = this;
            topp = new ObservableCollection<ClassMM>();
            startindex = dv = 1;
            topp.Add(new ClassMM() {PKId = dv, Name = "Test 1"});
            dv = 2;
            topp.Add(new ClassMM() {PKId = dv, Name = "Test 2"});
            dv = 3;
            topp.Add(new ClassMM() {PKId = dv, Name = "Test 3"});

            dv = 4;
            topp.Add(new ClassMM() {PKId = dv, Name = "Test 4"});

            lastindex = dv = 5;
            topp.Add(new ClassMM() {PKId = dv, Name = "Test 5"});


        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            lastindex = dv = dv++;

            topp.Add(new ClassMM() { PKId = dv, Name = musavebutton.Content.ToString() });
            foreach (var jk in topp.ToList())
            {
                MessageBox.Show(jk.Name);
            }
        }

        public class ClassMM : INotifyPropertyChanged
        {
            public string _name;
            public int _pkid;


            public int PKId
            {
                get { return _pkid; }
                set
                {
                    if (value != _pkid)
                    {
                        _pkid = value;
                        NotifyPropertyChanged("PKId");
                    }
                }
            }



            public string Name
            {
                get { return _name; }
                set
                {
                    if (value != _name)
                    {
                        _name = value;
                        NotifyPropertyChanged("Name");
                    }
                }
            }



            public event PropertyChangedEventHandler PropertyChanged;

            protected void NotifyPropertyChanged(String propertyName)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                }
            }
        }

不要看漏了,topp是一个ObservableCollection列表。我想将其绑定到ItemsControlitemsSource上。 - user2835256
非常抱歉,是我的错。我复制了你创建的第二个属性并对其进行了修改 =) - HichemSeeSharp
正如所说,您需要将DataConxtext设置为持有属性topp的类。我已经很久没有写WPF了,但是在XAML中,您不应该删除Path吗? <ItemsControl x:Name="lstItemsClassM" ItemsSource="{Binding topp, Mode=TwoWay} - Filip
@HichemCSharp 你在这里吗? - user2835256
@HichemCSharp,我已经删除了“path”,但还是不行。你的代码产生了异常:( - user2835256
显示剩余5条评论

3
这是错误的写法:ItemsSource="{Binding topp, Mode=TwoWay}"TwoWay 是指获取和设置绑定属性本身,即topp,而不是列表的内容。 ObservableList 已经内置了项添加/删除通知处理。在这种情况下,您不希望项控件干扰topp的值,因此正确的绑定只需使用{Binding topp}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接