use*_*552 3 wpf command messagebox mvvm icommand
我有一个按钮附加到视图模型中的命令。此按钮删除当前在列表视图中选择的行,因此我想在继续之前显示一个确认消息框。用户单击确定按钮(在消息框中)然后执行命令,否则,如果用户单击取消按钮附加命令不会被调用。是否可以?如果是这样怎么办?
<Button Name="btnDelete" Command="{Binding DeleteRowsCommand}"/>
Run Code Online (Sandbox Code Playgroud)
另一种可能性是在单击时和在视图模型中通过附加到放置在视图中的自定义消息框的属性调用命令,以使该自定义消息框在属性值为 true 时可见。但是,如何将按下了“确定”或“取消”按钮的视图发送回视图模型?
在执行命令之前,视图模型通常不需要知道用户有问题。如果是这种情况,您可以创建非常简单的自定义按钮类来仅显示消息框,如果用户单击是,则执行命令(或执行任何操作)。
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();
}
}
Run Code Online (Sandbox Code Playgroud)
在 XAML 中,您可以像这样使用按钮:
<components:YesNoButton Content="Delete rows" Command="{Binding DeleteRowsCommand}" Question="Do you really want to delete rows?" />
Run Code Online (Sandbox Code Playgroud)
编辑:解决这个问题的另一种方法是在 ViewModel 层中定义一些MessageBoxService并在 View 层中实现它。界面可能如下所示:
public interface IMessageBoxService
{
void ShowError(string messageBoxText);
void ShowWarning(string messageBoxText);
void ShowInformation(string messageBoxText);
}
Run Code Online (Sandbox Code Playgroud)
通过这种方式,您可以直接从 VM 显示消息框,而无需直接引用 WPF 库。
| 归档时间: |
|
| 查看次数: |
2701 次 |
| 最近记录: |