2012-04-07 76 views
0

(使用WPF應用程序/ WPF用戶控件)將文本從文本框保存到全局字符串。最好的方法來使用保存?

可以使用下面的代碼將文本從文本框保存到全局字符串。

private void commentBox_TextChanged(object sender, TextChangedEventArgs e) 
{ 
    Properties.Settings.Default.cmd01 = commentBox.Text; 

    //always save on every input change?? 
    Properties.Settings.Default.Save(); 
} 

,但我想知道現在是,在這種情況下,save調用的每個文字的變化。所以如果我理解正確的話,現在可以節省每個按鍵的時間。

我可以用更乾淨的方式做到這一點嗎?例如,當用戶離開文本框或什麼的焦點?

回答

1

正如您所建議的:訂閱UIElement.LostFocus EventKeyboard.LostKeyboardFocus Attached Event您的TextBox並保存在那裏。

private void commentBox_LostFocus(object sender, RoutedEventArgs e) 
{ 
    Properties.Settings.Default.Save(); 
} 

private void commentBox_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) 
{ 
    Properties.Settings.Default.Save(); 
} 
0

如果你要使用WPF你還不如趁綁定的基礎設施爲這樣的事情。您可以使用引發LostFocus

XAML的UpdateSourceTrigger:

<TextBox Text="{Binding Path=Settings.Command01, 
         Mode=OneWayToSource, 
         UpdateSourceTrigger=LostFocus}" /> 

C#:

public class BindableSettings : INotifyPropertyChanged 
    { 
     public string Command01 
     { 
       get { return Properties.Settings.Default.cmd01; } 
       set 
       { 
         if (Properties.Settings.Default.cmd01 == value) 
          return; 

         NotifyPropertyChanged("Command01"); 
       } 
     } 

     public void NotifyPropertyChanged(string prop) 
     { 
      Properties.Settings.Default.Save(); 
      //Raise INPC event here... 
     } 

    }