WPF TextChanged 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21787378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF TextChanged event
提问by user2729661
I have a TextBox and a Button inside my WPF application. When the user clicks on the button it saves the textbox's text value into a txt file. So, basically when the user inserts something in the TextBox, the TextChaned event is triggered. The problem is, for example, if the user types "Daniel" and clicks on the button, every single combination of user's input is also saved. How can I get rid of this?
我的 WPF 应用程序中有一个 TextBox 和一个 Button。当用户单击按钮时,它会将文本框的文本值保存到 txt 文件中。所以,基本上当用户在 TextBox 中插入一些东西时,TextChaned 事件就会被触发。问题是,例如,如果用户键入“Daniel”并单击按钮,则用户输入的每个组合也会被保存。我怎样才能摆脱这个?
The text file contains:
文本文件包含:
D
Da
Dan
Dani
Danie
Daniel
How can I save only the last string (Daniel) or is there any other event handler for my problem? Btw, this is actually a list, and I'm using the Add method.
我怎样才能只保存最后一个字符串(丹尼尔)或者是否有其他事件处理程序可以解决我的问题?顺便说一句,这实际上是一个列表,我使用的是 Add 方法。
Code, as requested:
代码,根据要求:
// Button, just ignore all the crap inside
private void saveChangesButton_Click(object sender, RoutedEventArgs e)
{
System.IO.File.WriteAllLines(@System.IO.File.ReadAllText(@System.IO.Directory.GetCurrentDirectory() + "/dir.txt") + "/commandline.txt", checkedValues);
}
// List
private List<String> checkedValues = new List<String>();
// TextChanged
private void sWidth_TextChanged(object sender, TextChangedEventArgs e)
{
checkedValues.Add(sWidth.Text);
}
回答by Derek W
You want this to be handled by your Button's Clickevent and not the TextBox's TextChangedevent.
您希望这由您的 ButtonClick事件而不是 TextBoxTextChanged事件来处理。
Like this:
像这样:
private void saveButton_Click(object sender, RoutedEventArgs e)
{
using (var streamWriter = new StreamWriter("yourtextfile.txt", true))
{
streamWriter.WriteLine(textBox.Text);
}
}
回答by ?ukasz Motyczka
I would try something like that:
我会尝试这样的事情:
// List
private List<String> checkedValues = new List<String>();
public int nTextboxChanged = 0;
// Button, just ignore all the crap inside
private void saveChangesButton_Click(object sender, RoutedEventArgs e)
{
if(nTextboxChanged == 1)
{
checkedValues.Add(sWidth.Text);
System.IO.File.WriteAllLines(@System.IO.File.ReadAllText(@System.IO.Directory.GetCurrentDirectory() + "/dir.txt") + "/commandline.txt", checkedValues);
}
}
// TextChanged
private void sWidth_TextChanged(object sender, TextChangedEventArgs e)
{
nTextboxChanged = 1;
}
回答by Shoe
You don't need the TextChanged event at all.
您根本不需要 TextChanged 事件。
xaml
xml
<TextBox Name="textToSave" />
<Button Click="saveToTextFile" />
cs
CS
private void saveToTextFile(...){
string text = textToSave.Text;
//code to save to text file
}

