在WinForms中,我们可以为按钮指定DialogResult。在WPF中,我们可以仅在XAML中声明Cancel按钮:
<Button Content="Cancel" IsCancel="True" />对于其他人,我们需要捕获ButtonClick并像这样编写代码:
private void Button_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = true;
}我使用的是MVVM,所以我只有windows的XAML代码。但是对于模式窗口,我需要编写这样的代码,我不喜欢这样。在WPF中有没有更优雅的方式来做这样的事情呢?
发布于 2010-12-18 01:54:43
你可以用一个attached behavior来保持你的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>发布于 2010-03-30 15:04:28
另一种方法是使用Popup Control
试试这个tutorial。
https://stackoverflow.com/questions/2543014
复制相似问题