WPF对话结果声明?
在WinForms中,我们可以为按钮指定DialogResult。在WPF中,我们可以在XAML中声明仅取消按钮:WPF对话结果声明?,wpf,modal-dialog,Wpf,Modal Dialog,在WinForms中,我们可以为按钮指定DialogResult。在WPF中,我们可以在XAML中声明仅取消按钮: <Button Content="Cancel" IsCancel="True" /> 我使用的是MVVM,所以我只有适用于windows的XAML代码。但是对于模态窗口,我需要编写这样的代码,我不喜欢这样。在WPF中有没有更优雅的方法来做这些事情?另一种方法是使用 试试这个。您可以使用一个来保持MVVM的干净。您附加行为的C#代码可能如下所示: public sta
<Button Content="Cancel" IsCancel="True" />
我使用的是MVVM,所以我只有适用于windows的XAML代码。但是对于模态窗口,我需要编写这样的代码,我不喜欢这样。在WPF中有没有更优雅的方法来做这些事情?另一种方法是使用 试试这个。您可以使用一个来保持MVVM的干净。您附加行为的C#代码可能如下所示:
public static class DialogBehaviors
{
private static void OnClick(object sender, RoutedEventArgs e)
{
var button = (Button)sender;
var parent = VisualTreeHelper.GetParent(button);
while (parent != null && !(parent is Window))
{
parent = VisualTreeHelper.GetParent(parent);
}
if (parent != null)
{
((Window)parent).DialogResult = true;
}
}
private static void IsAcceptChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var button = (Button)obj;
var enabled = (bool)e.NewValue;
if (button != null)
{
if (enabled)
{
button.Click += OnClick;
}
else
{
button.Click -= OnClick;
}
}
}
public static readonly DependencyProperty IsAcceptProperty =
DependencyProperty.RegisterAttached(
name: "IsAccept",
propertyType: typeof(bool),
ownerType: typeof(Button),
defaultMetadata: new UIPropertyMetadata(
defaultValue: false,
propertyChangedCallback: IsAcceptChanged));
public static bool GetIsAccept(DependencyObject obj)
{
return (bool)obj.GetValue(IsAcceptProperty);
}
public static void SetIsAccept(DependencyObject obj, bool value)
{
obj.SetValue(IsAcceptProperty, value);
}
}
您可以使用XAML中的属性,代码如下:
<Button local:IsAccept="True">OK</Button>
OK
Duplicate:我以前觉得在MVVM中使用代码隐藏是一种方式,但老实说,我认为在代码隐藏中设置一个标志是最优雅的解决方案。为什么要反抗它。写一个复杂的附加行为来获取很少的收益是没有意义的。我不知道他为什么没有标记你的答案,但我会投票选择有用的MVVM样式的接受按钮。交互行为可以做到这一点,但对于这么简单的事情来说,这太冗长了。
<Button local:IsAccept="True">OK</Button>