因此,在创建FirstKeyCombo之后,添加PropertyChangedEventhandler
FirstKeyCombo.PropertyChanged += OnFirstKeyComboPropertyChanged;
应该是这样的:
private void OnFirstKeyComboPropertyChanged(object sender, PropertyChangedEventArgs e)
{
//remove the handler
FirstKeyCombo.PropertyChanged -= OnFirstKeyComboPropertyChanged;
//create new object because of referential equlity check in WPF
FirstKeyCombo = new KeyCombo(FirstKeyCombo.ModifierKeys, FirstKeyCombo.Key);
//add the handler to the new object
FirstKeyCombo.PropertyChanged += OnFirstKeyComboPropertyChanged;
}
RaisePropertyChanged(nameof(FirstKeyCombo));
至于评论,这就是反思的方式。KeyCombo.名称必须是属性的名称。
private void OnFirstKeyComboPropertyChanged(object sender, PropertyChangedEventArgs e)
{
KeyCombo combo = sender as KeyCombo;
//remove the handler
combo.PropertyChanged -= OnFirstKeyComboPropertyChanged;
//create new object because of referential equlity check in WPF
combo = new KeyCombo(combo.ModifierKeys, combo.Key, combo.Name);
//add the handler to the new object
combo.PropertyChanged += OnFirstKeyComboPropertyChanged;
//Get the ViewModel-Type
Type t = ViewModel.GetType();
//Get the property with the name
PropertyInfo pi = t.GetProperty(combo.Name);
//set the value of the property
pi.SetValue(ViewModel,combo);
}
或者用字典。也KeyCombo.名称必须是属性的名称。
private void OnFirstKeyComboPropertyChanged(object sender, PropertyChangedEventArgs e)
{
KeyCombo combo = sender as KeyCombo;
//remove the handler
combo.PropertyChanged -= OnFirstKeyComboPropertyChanged;
//create new object because of referential equlity check in WPF
combo = new KeyCombo(combo.ModifierKeys, combo.Key, combo.Name);
//add the handler to the new object
combo.PropertyChanged += OnFirstKeyComboPropertyChanged;
dictionaryWithAllCombos[combo.Name] = combo;
RaisePropertyChanged(combo.Name);
}
在ViewModel中
public FirstKeyCombo FirstKeyCombo
{
get { return dictionary["FirstKeyCombo"]; }
set
{
dictionaryWithAllCombos["FirstKeyCombo"] = value;
RaisePropertyChanged(nameof(FirstKeyCombo));
}
}