C# 绑定到(可能)代码中的null属性而不更新ModelView
我有一个与Singleton属性的绑定,如下所示:C# 绑定到(可能)代码中的null属性而不更新ModelView,c#,wpf,xaml,binding,C#,Wpf,Xaml,Binding,我有一个与Singleton属性的绑定,如下所示: <ComboBox ItemsSource="{Binding SourceList, UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Source={x:Static local:MySingleton.Instance}, UpdateSourceTrigger=PropertyCha
<ComboBox ItemsSource="{Binding SourceList, UpdateSourceTrigger=PropertyChanged}"
SelectedItem="{Binding Source={x:Static local:MySingleton.Instance}, UpdateSourceTrigger=PropertyChanged,
Path=PossibleNullProperty.PossibleNullProperty.PossibleNullProperty.Source}"
Width="Auto" />
public string Source
{
get { return MySingleton.Instance.PossibleNullProperty?.PossibleNullProperty?.PossibleNullProperty?.Source; }
set
{
MySingleton.Instance.PossibleNullProperty.PossibleNullProperty.PossibleNullProperty.Source = value;
RaisePropertyChanged();
MyCommand.RaiseCanExecuteChanged();
}
}
现在的问题是,在绑定发生时,链中的属性为null,因此组合框SelectedItem无法访问“Source”属性。
在应用程序运行时,这可能会更改,并且可以访问“Source”属性,但不会更新ModelView
我怎样才能解决我的问题
谢谢将此添加到您的ViewModel中,您会做得很好:
CommandManager.RequerySuggested += CommandManager_RequerySuggested;
private void CommandManager_RequerySuggested(object sender, EventArgs e)
{
this.MyCommand.CanExecute = "..."
}
UI中的每一次更改都将调用CommandManager\u RequerySuggested
由于此事件是静态的,因此它将仅作为弱引用保留处理程序
别忘了使用async/await:对于有相同问题的人,这就是我的DelegateCommand类现在的样子,它工作得非常好,感谢dev hedgehog的解决方案
public class DelegateCommand<T> : System.Windows.Input.ICommand where T : class
{
private readonly Predicate<T> _canExecute;
private readonly Action<T> _execute;
public DelegateCommand(Action<T> execute)
: this(execute, null)
{
}
public DelegateCommand(Action<T> execute, Predicate<T> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
if (_canExecute == null)
return true;
return _canExecute((T)parameter);
}
public void Execute(object parameter)
{
_execute((T)parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
}
将视图所需的所有数据放入视图模型或代码中。但是如果嵌套属性发生变化,那么我必须订阅整个链中的PropertyChanged事件,并且当属性发生变化时,我必须在我的ViewModel中设置新值……用一种最简单的方法,您必须确保属性链中的每个类型都实现INotifyPropertyChanged,并在您的VM上公开MySingleton作为属性,而绑定路径将是从MySingleton到所需属性的整个路径。否则,您将以某种方式侦听每个属性的通知。整个链中的每个对象都实现INotifyPropertyChanged,但“在您的VM上公开MySingleton作为属性”是什么意思?您好,这部分解决了我的问题,将调用CanExecuteChangeEvent,但绑定不会更新,我做错了什么?您问如何从ViewModel触发CanExecute。这就是方法:如果您希望绑定知道静态属性何时更改,我建议您看看如何正确绑定到静态属性。不管怎样,解决方案是有效的,我只需要删除指向嵌套属性的属性,并再次直接绑定到单例。谢谢你的解决方案!