如何使用命令按钮关闭userControl

时间:2011-12-05 10:26:02

标签: wpf user-controls wpf-controls command

我正在使用3个文件:

1-)Simple.xaml,它包含

<Button x:Name="OkButton"
        Command="{Binding OkSettingsCommand}"
        IsDefault="True"
        Content="OK" />

2-)Simple.xaml.cs ...它是空的,除了具有InitializeComponent()方法的构造函数

3-)具有ICommand OkSettingsCommand;的SimpleViewModel ... 在构造函数

中初始化
OkSettingsCommand = new ICommand(OnOKSettings);

使用此功能:

public void OnOKSettings()
{

}

如何在单击按钮后关闭用户控件?

1 个答案:

答案 0 :(得分:0)

试试这个

像这样创建关闭行为

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);
    }
}

在View Model中创建一个属性,让它成为

 private bool closeMe=false ;
    public bool CloseMe
    {
        get
        {
            return closeMe;
        }
        set
        {
            closeMe = value;
            RaisePropertyChanged("CloseMe");
        }
    }

并在View中将CloseMe值绑定到Behavior中。当您单击Button时,使CloseMe = True,这将关闭当前窗口

例如

<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>