我将此嵌套绑定绑定到对象 ItemDescription ,默认情况下, MyEvidence 属性为null,因此将其显示为空白,但是只要将其值设置为EvidenceDTO对象itemDescription值将按预期显示。
现在,当我再次将MyEvidence属性设置为null时,我希望ItemDescription文本再次为空白,但这不会发生,显然它不知道父对象现在已更改/为空,因此子对象不应出现了。我在ViewModel类上设置了 INotifyPropertyChanged ,因此在EvidenceDTO中的MyEvidence属性和ItemDescription属性上都设置了一个名为 Observable
的帮助程序类。Xaml绑定
<TextBlock Text="{x:Bind ViewModel.MyEvidence.ItemDescription, Mode=OneWay}" />
像这样在页面后端初始化ViewModel
public MainViewModel ViewModel { get; } = new MainViewModel();
我的视图模型代码
public class MainViewModel : Observable
{
private EvidenceDTO _myEvidence;
public EvidenceDTO MyEvidence { get => _myEvidence; set => Set(ref _myEvidence, value); }
}
证据DTO
public class EvidenceDTO : Observable
{
private string _itemDescription;
public string ItemDescription { get => _itemDescription; set => Set(ref _itemDescription, value); }
}
可观察的班级
public class Observable : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void Set<T>(ref T storage, T value, [CallerMemberName]string propertyName = null)
{
if (Equals(storage, value))
{
return;
}
storage = value;
OnPropertyChanged(propertyName);
}
protected void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
我以ItemDescription为例,还有更多EvidenceDTO属性以类似方式显示在UI上,因此我需要一些通用解决方案,在绑定路径的所有级别上引发属性更改通知。
答案 0 :(得分:1)
似乎将MyEvidence设置为null时,它仍将显示以前缓存的值,而当重新初始化MyEvidence时,它将根据属性值重新显示。因此,如果您想再次将ItemDescription文本显示为空白,则最好重新初始化MyEvidence,例如:
private void Button_Click(object sender, RoutedEventArgs e)
{
ViewModel.MyEvidence = new EvidenceDTO();
}
如果您有一层以上的嵌套模型,则可以在嵌套模型的每一层中按如下所示设置模型。将MyEvidence设置为null时,它将触发MyEvidence的get方法,然后在get方法中将其重新初始化。
public EvidenceDTO MyEvidence
{
get
{
if (_myEvidence == null)
{
_myEvidence = new EvidenceDTO();
}
return _myEvidence;
}
set => Set(ref _myEvidence, value);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
ViewModel.MyEvidence = null;
}
答案 1 :(得分:1)
设置属性ViewModel.MyEvidence = null,不会处理MyEvidence对象。对象的引用超出范围,您应该尝试对ViewModel.MyEvidence提供新的引用。尝试以下一个=> ViewModel.MyEvidence = new EvidenceDTO();