繁体   English   中英

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

[英]Wpf two way binding in listbox

遗憾的是,尝试在列表框中进行两种方式的绑定不起作用。 这是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>

这是viewmodel和个人代码:

 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;

        }

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

更改就足够了:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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