我有一个按钮附加到 View 模型中的命令。此按钮删除当前在 ListView 中选择的行,因此我想在继续之前显示一个确认消息框。用户是否单击确定按钮(在消息框中)然后执行命令,否则,如果用户单击取消按钮,则不调用附加的命令。可能吗?如果有怎么办?
<Button Name="btnDelete" Command="{Binding DeleteRowsCommand}"/>
另一种可能性是通过附加到放置在 View 中的自定义消息框的属性在单击时和在 View 模型中调用命令,以使该自定义消息框在属性值为 true 时可见。但是,我怎样才能将按下的“确定”或“取消”按钮发送回 View 模型?
最佳答案
在执行命令之前, View 模型通常不需要知道用户有问题。如果是这种情况,您可以创建非常简单的自定义按钮类来仅显示消息框,如果用户单击"is",则执行命令(或执行任何操作)。
public class YesNoButton : Button
{
public string Question { get; set; }
protected override void OnClick()
{
if (string.IsNullOrWhiteSpace(Question))
{
base.OnClick();
return;
}
var messageBoxResult = MessageBox.Show(Question, "Confirmation", MessageBoxButton.YesNo);
if (messageBoxResult == MessageBoxResult.Yes)
base.OnClick();
}
}
在 XAML 中,您可以像这样使用按钮:
<components:YesNoButton Content="Delete rows" Command="{Binding DeleteRowsCommand}" Question="Do you really want to delete rows?" />
编辑:解决这个问题的另一种方法是在 ViewModel 层中定义一些 MessageBoxService 并在 View 层中实现它。界面可能如下所示:
public interface IMessageBoxService
{
void ShowError(string messageBoxText);
void ShowWarning(string messageBoxText);
void ShowInformation(string messageBoxText);
}
通过这种方式,您可以直接从 VM 显示消息框,而无需直接引用 WPF 库。
关于wpf - MVVM 在执行附加到按钮的命令之前显示确认消息框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45325941/