将文本框中的文本保存到全局字符串.使用保存的最佳方式

本文关键字:保存 文本 最佳 方式 字符串 全局 | 更新日期: 2023-09-27 18:30:26

(Using WPF Application/WPF UserControl)

可以使用下面的代码将文本框中的文本保存到全局字符串。

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。因此,如果我理解正确,它现在会节省每个按下的键。

我能用更干净的方式做到这一点吗?例如,当用户从文本框或其他内容离开焦点时?

将文本框中的文本保存到全局字符串.使用保存的最佳方式

正如您所建议的:订阅您TextBox的UIElement.LostFocus Event 或 Keyboard.LostKeyboardFocus 附加事件并在那里进行保存。

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

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

如果要使用 WPF,不妨利用绑定基础结构来实现此类操作。您可以使用 LostFocus 的 UpdateSourceTrigger

XAML:

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