视图包含几个按钮。 在ViewModel中,“IsShiftLock”属性驻留并动态创建绑定。
public bool IsShiftLock {
get { return _isShiftLock; }
set {
if (value != _isShiftLock) {
_isShiftLock = value;
Notify("IsShiftLock");
}
}
}
Notify是BaseViewModel中的方法。
public abstract class BaseViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void Notify(string sPropertyName)
{
PropertyChangedEventHandler changedEventHandler = this.PropertyChanged;
if (changedEventHandler == null)
return;
changedEventHandler((object) this, new PropertyChangedEventArgs(sPropertyName));
}
}
Binding b2 = new Binding {
Source = this,
Path = new PropertyPath("IsShiftLock"),
Converter = new ShiftLockToTextConverter()
};
b2.Mode = BindingMode.OneWay;
curKeyView.Button.SetBinding(ContentControl.ContentProperty, b2);
IsShiftLock正常更改,但转换器调用仅发生一次。 据我了解,应该适当通知绑定更改。怎么做到这一点?
更新1:
查看方:
private readonly KeyboardViewModel viewModel;
public static KeyboardViewModel ViewModelInstance;
public VirtualKeyboard() {
Loaded += OnLoaded;
InitializeComponent();
viewModel = new KeyboardViewModel();
DataContext = viewModel;
ViewModelInstance = viewModel;
}
答案 0 :(得分:1)
问题在于绑定Source
属性。您应该将其设置为this.DataContext
或其他来源,它将起作用。
Binding b2 = new Binding {
Source = this.DataContext,
Path = new PropertyPath("IsShiftLock"),
Converter = new ShiftLockToTextConverter()
};
答案 1 :(得分:0)
问题在于KeyViewModel本身继承了BaseViewModel并订阅了PropertyChangedEvent。我不了解整个情况,但我解决了这个问题。
每个KeyViewModel都明确订阅了PropertyChangedEvent,因此,不知何故,我试图为Shift按钮和Caps Lock动态设置的绑定被击倒或者其他东西。不幸的是,我不了解幕后的整体情况。