WPF列表框中的两种方式绑定

时间:2018-10-20 17:48:47

标签: c# wpf

不幸的是,

试图在列表框中进行两种方式的绑定不起作用。 这是xaml代码:

 <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>

这是视图模型和人员代码:

 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;
}

和MainWindow:

 public MainWindow()
        {

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

        }

我不知道出了什么问题,试图绑定属性“名称”,但是它不起作用。拜托,让我知道怎么了。

1 个答案:

答案 0 :(得分:1)

更改就足够了:

 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;
            }
        }
    }