对于所有这些,您将使用绑定作为“通信”的方法。例如,可能会根据您在 ViewModel 中设置的属性显示或隐藏确认消息。
这是视图
<Window.Resources>
<BoolToVisibilityConverter x:key="boolToVis" />
</Window.Resources>
<Grid>
<TextBox Text="{Binding Comment, Mode=TwoWay}" />
<TextBlock Visibility="{Binding IsCommentConfirmationShown,
Converter={StaticResource boolToVis}"
Text="Are you sure you want to cancel?" />
<Button Command="CancelCommand" Text="{Binding CancelButtonText}" />
</Grid>
这是你的 ViewModel
// for some base ViewModel you've created that implements INotifyPropertyChanged
public MyViewModel : ViewModel
{
//All props trigger property changed notification
//I've ommited the code for doing so for brevity
public string Comment { ... }
public string CancelButtonText { ... }
public bool IsCommentConfirmationShown { ... }
public RelayCommand CancelCommand { ... }
public MyViewModel()
{
CancelButtonText = "Cancel";
IsCommentConfirmationShown = false;
CancelCommand = new RelayCommand(Cancel);
}
public void Cancel()
{
if(Comment != null && !IsCommentConfirmationShown)
{
IsCommentConfirmationShown = true;
CancelButtonText = "Yes";
}
else
{
//perform cancel
}
}
}
这不是一个完整的示例(唯一的选择是肯定的!:)),但希望这说明您的 View 和您的 ViewModel 几乎是一个实体,而不是两个互相打电话的实体。
希望这可以帮助。