WPF:按下按钮时从绑定属性更新ListBox,而不是自动更新

时间:2015-09-17 23:10:42

标签: wpf

给定以下类(其中ViewModelBase包含INotifyPropertyChanged成员)

namespace WpfApplication1
{
    class ViewModel : ViewModelBase
    {
        private Person selectedPerson;

        public ObservableCollection<Person> Persons { get; set; }

        public Person SelectedPerson
        {
            get
            {
                return selectedPerson;
            }
            set
            {
                selectedPerson = value;
                OnPropertyChanged("SelectedPerson");
            }
        }

        public ViewModel()
        {
            Persons = new ObservableCollection<Person>();
            Persons.Add(new Person { FirstName = "John", LastName = "Smith" });
            Persons.Add(new Person { FirstName = "Jane", LastName = "Jones" });

            SelectedPerson = new Person();
        }
    }

    class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

以下XAML

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:vm="clr-namespace:WpfApplication1"
    Title="MainWindow" Height="350" Width="525">
  <Window.DataContext>
    <vm:ViewModel />
  </Window.DataContext>
  <Grid>
    <StackPanel>
      <ListBox ItemsSource="{Binding Persons}"
               DisplayMemberPath="FirstName"
               SelectedItem="{Binding SelectedPerson}"/>
      <StackPanel DataContext="{Binding SelectedPerson}">
        <TextBox Text="{Binding FirstName}" />
        <TextBox Text="{Binding LastName}" />
      </StackPanel>
    </StackPanel>
  </Grid>
</Window>

如果更改了绑定到FirstName的TextBox中的值,则更改将自动反映在ListBox中。假设我添加了一个Button控件和相关的Command,那么只有在按下该Button的情况下,才有办法将更改后的值传播到ListBox吗?

0 个答案:

没有答案