2011-12-05 42 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>