只是試試這個
像這樣創建
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開發人員 –