0

我有两个窗口:父母和孩子。父窗口中有列表框。

主视图:

<Button x:Name="btnUpdate" Content="Update"
                Command="{Binding Path=MyCommand}" CommandParameter="{Binding ElementName=lstPerson, Path=SelectedItem}" />

<ListBox x:Name="lstPerson" ItemsSource="{Binding Persons}" />

我正在尝试通过使用带有参数的 ICommand 来更改选定的 Person 双向更新。

人物视图模型:

        private ICommand myCommand;
        public ICommand MyCommand
        {
            get
            {
                if (myCommand == null)
                {
                    myCommand = new RelayCommand<object>(CommandExecute, CanCommandExecute);
                }

                return myCommand;

            }

        }

        private void CommandExecute(object parameter)
        {

            var ew = new EditWindow()
                         {
                             DataContext =
                                 new EditViewModel()
                                     {
                                         Name = ((Person) parameter).Name, 
                                         Address = ((Person) parameter).Address
                                     }
                         };

            ew.Show();

        }

但是在列表框中选择的 Person 实例没有改变。我需要向 xaml 或 PersonViewModel 写入什么才能使其正常工作?

附言

这是我的人

    public class Person : INotifyPropertyChanged
    {
        private string name;
        private string address;

        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
                OnPropertyChanged("Name");
            }
        }
        public string Address
        {
            get
            {
                return address;
            }
            set
            {
                address = value;
                OnPropertyChanged("Address");
            }
        }
    }
4

1 回答 1

2

该命令的执行命令参数错误。当您绑定到绑定到SelectedItem的列表时ObservableCollection<PersonViewModel>,所选项目将是类型PersonViewModel。尝试相应地初始化ICommand asRelayCommand and modifyCommandExecute(PersonViewModel person)`。

其次,ICommand 是在 PersonViewModel 上定义的,但 Command 应该在持有该Persons集合的 ViewModel 上。因此,要么移动命令,要么在 PersonViewModel 上定义命令,以修改特定的 ViewModel,它是打开的。比你可以节省的CommandParameter,但像这样绑定命令:

CommandExecute这样的事情:

private void CommandExecute(object parameter)
{
    // Modify this, ie. this.Name = something
}

最后一件事,您的 ViewModel 还需要实现 INotifyPropertyChanged 并转发模型更改通知。否则不会反映更改,除非绑定到实际属性更新它。例如,如果您像这样绑定

<TextBox Text="{Binding Name, Mode=TwoWay}" />

ViewModel 上的Name属性将被更新,但如果你调用

Name = "ChuckNorris"

在您的CommandExecute(..)方法中,不会更新 UI,因为不会触发任何更改通知。

于 2013-05-22T06:33:08.020 回答