如何在 WPF C# 中清除用户控件中的文本框?
我有一个用户控件,其中有一个文本框,我使用主窗体上的清除按钮来清除整个主窗口中的信息。我想在单击清除按钮后清除用户控件中的文本框。我还没有找到一个简单的方法来做到这一点。我尝试在 C# 中引用控件的名称,后跟“.”。但是文本框的名称不会显示。任何帮助将不胜感激!
I have a user control that has a textbox in it, and i am using a clear button on my main form to clear information from the entire main window. i would like to clear the textbox in the user control once the clear button is clicked as well. i havent found an easy way to do this. i have tried referencing the control's name in c# followed by a "." however the name of the text box does not show up. any help would be appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
WPF 将
UserControl
中的控件声明为private
。要使您的TextBox
public
,您可以使用FieldModifier
声明它,如下所示:其中
x
是 xaml 命名空间xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
。但是,清除TextBox
的推荐方法是将其绑定到属性,然后清除该属性。WPF declares controls in a
UserControl
asprivate
. To make yourTextBox
public
you declare it with aFieldModifier
as in:where
x
is the xaml namespacexmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
. However the recommended way of clearing aTextBox
is to bind it to a property and then clear the property.您不应尝试从外部类或代码直接访问 UserControl 中的控件。简单的机制是向 UserControl 添加 Clear() 方法,该方法清除 UserControl 内的所有相关控件和信息。
You should not try to directly access controls within a UserControl from external classes or code. The simple mechanism would be to add a Clear() method to the UserControl which clears all relevant controls and information inside the UserControl.
文本框可以绑定到 UserControl 的 DataContext。因此,清除它的一种方法可能是将绑定到 TextBox 的 Text 属性的属性设置为空字符串。
The textbox could be bound to the DataContext of the UserControl. So a way of clearing it might be setting the property that is bound to the Text property of the TextBox to an empty string.