只是试试这个
像这样创建
public static class WindowCloseBehavior
{
public static readonly DependencyProperty IsOpenProperty =
DependencyProperty.RegisterAttached("IsOpen", typeof(bool), typeof(WindowCloseBehavior),
new PropertyMetadata(IsOpenChanged));
private static void IsOpenChanged(DependencyObject obj,
DependencyPropertyChangedEventArgs args)
{
Window window = Window.GetWindow(obj);
if (window != null && ((bool)args.NewValue))
window.Close();
}
public static bool GetIsOpen(Window target)
{
return (bool)target.GetValue(IsOpenProperty);
}
public static void SetIsOpen(Window target, bool value)
{
target.SetValue(IsOpenProperty, value);
}
}
关闭行为创建视图模型的属性让它成为
private bool closeMe=false ;
public bool CloseMe
{
get
{
return closeMe;
}
set
{
closeMe = value;
RaisePropertyChanged("CloseMe");
}
}
,并在查看刚刚绑定CloseMe值成行为。当你点击按钮使CloseMe =真,这将关闭当前窗口
如
<Window x:Class="WpfApplication12.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Behavior="clr-namespace:WpfApplication12"
Behavior:WindowCloseBehavior.IsOpen="{Binding CloseMe}"
Title="Window1" Height="300" Width="300">
<Grid>
<CheckBox IsChecked="{Binding CloseMe}" Content="Close" Margin="5"></CheckBox>
</Grid>
你的意思是关闭在其中放置用户控件的窗口? –
是的,我是一名新的WPF开发人员 –