简体   繁体   中英

Wpf two way binding in listbox

trying to do two way binding in the listbox unfortunately does not work. Here's the xaml code:

 <ListBox Margin="19,0,21,149" ItemsSource="{Binding Items}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBox Text="{Binding Path=Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
                        <TextBlock Text="{Binding Path=Age}" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

here's the viewmodel and person code:

 public class ViewModel
    {
        public ObservableCollection<Person> Items
        {
            get
            {
                return new ObservableCollection<Person>
            {
                new Person { Name = "P1", Age = 1 },
                new Person { Name = "P2", Age = 2 }
            };
            }
        }
    }
public class Person : INotifyPropertyChanged
{
    public string _name;
    public int Age { get; set; }
    public string Name
    {
        get
        {
            return _name;
        }
        set
        {
            if (value != _name)
            {
                _name = value;
                OnPropertyChanged("Name");
            }
        }
    }
    private void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
}

and MainWindow:

 public MainWindow()
        {

            InitializeComponent();
            model = new ViewModel();
            this.DataContext = model;

        }

I do not know what is wrong, trying to bind the property "Name", but it does not work. Please, let me know what may be wrong.

It was enough to change:

 public class ViewModel
    {
        ObservableCollection<Person> _items = new ObservableCollection<Person>
            {
                new Person { Name = "P1", Age = 1 },
                new Person { Name = "P2", Age = 2 }
            };
        public ObservableCollection<Person> Items
        {
            get
            {
                return _items;
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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