2011-12-05 38 views
0

我使用3个文件关闭用户控件:如何使用命令按钮

1)Simple.xaml,它包含

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

2-)Simple.xaml.cs ......这是空的,不同之处在于具有一个InitializeComponent()方法构造

3-)SimpleViewModel ...具有一个ICommand OkSettingsCommand; ,其在构造初始化

使用此功能

public void OnOKSettings() 
{ 

} 

我怎样才能关闭按钮后,用户控件被点击?

+1

你的意思是关闭在其中放置用户控件的窗口? –

+0

是的,我是一名新的WPF开发人员 –

回答

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

关闭行为创建视图模型的属性让它成为

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>