我有一个WFP项目,我正在使用MVVM模式。 我有在CustomerView UserControl中使用的AddressView用户控件。
<my:AddressVeiw Width="340" DataContext="AddressViewModel"/>
我的AddressVeiw userControl有一个AddressViewModel,而CustomerView有一个CustomerViewModel
CustomerViewModel代码
public DelegateCommand<object> SaveCommand { get; set; } private string firstName; public string FirstName { get { return firstName; } set { firstName = value; RaisePropertyChanged("FirstName"); SaveCommand.RaiseCanExecuteChanged(); } } private string lastName; public string LastName { get { return lastName; } set { lastName = value; RaisePropertyChanged("LastName"); SaveCommand.RaiseCanExecuteChanged(); } } private AddressViewModel addressViewModel; public AddressViewModel AddressViewModel { get { return addressViewModel; } set { addressViewModel = value; } } private string middleName; public string Middlename { get { return middleName; } set { middleName = value; RaisePropertyChanged("MiddleName"); SaveCommand.RaiseCanExecuteChanged(); } } private string fullName; public string FullName { get { return fullName; } set { fullName = value; RaisePropertyChanged("FullName"); } } private void InitializeCommands() { SaveCommand = new DelegateCommand<object>(OnSaveCommand, CanSaveExcute); } private bool CanSaveExcute(object obj) { if (string.IsNullOrEmpty(firstName) ||string.IsNullOrEmpty(lastName)) return false; return true; } private void OnSaveCommand(object obj) { FullName = FirstName + " " + LastName; } }
AddressViewModel的代码
private ObservableCollection<Country> countryList = new ObservableCollection<Country>(); public ObservableCollection<Country> CountryList { get { return countryList; } set { countryList = value; } } public DelegateCommand<object> SaveCommand { get; set; } private void Load() { try { CountryList = (new CountryRepository().GetAll()); } catch (Exception ex) { OnSetStatusBarText("Error: " + ex.Message.ToString()); } } private void OnSetStatusBarText(string message) { var evt = eventAgg.GetEvent<StatusBarMessageEvent>(); evt.Publish(message); } private void InitializeCommands() { SaveCommand = new DelegateCommand<object>(OnSaveCommand, CanSaveExcute); } private bool CanSaveExcute(object obj) { return true; } private void OnSaveCommand(object obj) { }
我可以将AdddressViewModel挂钩到我的AddressView,Customer Works正常...... 必须采取什么措施来解决这个问题? 感谢
答案 0 :(得分:1)
你很亲密,但你需要一个绑定:
<my:AddressVeiw Width="340" DataContext="{Binding AddressViewModel}"/>
答案 1 :(得分:1)
您需要为AddressView的DataContext使用绑定表达式。而不是......
<my:AddressVeiw Width="340" DataContext="AddressViewModel"/>
...试试这个......
<my:AddressVeiw Width="340" DataContext="{Binding AddressViewModel}"/>