这是用于测试目的的短代码。问题是 UI 没有显示与 ViewModelB 绑定的标签中的文本。在调试中,当我在 xaml 中将鼠标悬停在标签中的文本上时,我看到正确的绑定数据在那里,但 UI 根本不会显示。使用 ViewModelA 没有问题。
在 XAML 中:
<StackLayout>
<StackLayout>
<StackLayout.BindingContext>
<testbinding:ViewModelA/>
</StackLayout.BindingContext>
<Button Command ="{Binding Get}"/>
</StackLayout>
<StackLayout>
<StackLayout.BindingContext>
<testbinding:ViewModelB/>
</StackLayout.BindingContext>
<Label Text="{Binding Metadata}"/>
</StackLayout>
ViewModelA:其中 BaseViewModel 是 INotifyPropertyChanged 接口
public ViewModelA:BaseViewModel
{
public ViewModelA()
{
Get = new Command(SendText);
vmB = new ViewModelB();
}
ViewModelB vmB;
public ICommand Get { get; }
private void SendText()
{
string data = "someText";
vmB.GetMetadata(data);
}
}
ViewModelB 是这样的:
class ViewModelB:BaseViewModel
{
private string _metadata = string.Empty;
public string Metadata
{
get { return _metadata; }
set
{
_metadata = value;
OnPropertyChanged();
}
}
GetMetadata()
{
Metadata = "Some text";
}
}
在 ViewModelA 中有更多我需要的属性,而在 ViewModelB 中只是一个从函数获取数据的属性。我可以从它们中只制作一个 ViewModel,效果很好,但我试图让它们更小且更有条理。我已经尝试了很多场景并且变得非常令人沮丧。感谢您的帮助。