带有 TextBox 的 WPF UserControl,使用 TextChanged 事件 C#
我有一个客户用户控件,它是一个带有标签的 TextBox
(Border
包裹在 Label
和 TextBox
周围,其中 TextBox
带有 < code>TextBox 与标签重叠)。我发现了一些关于如何在从 UserControl 调用时使 TextChanged
函数正常工作的(有效)示例。
只是文本框片段:
<TextBox
FontSize="{Binding Path=DefaultFontSize}"
Style="{StaticResource WatermarkTextBox}"
Padding="{Binding Path=TextPadding}"
Tag="{Binding Path=TextValue}"
/>
我尝试使用 RoutedEventHandler 就像我对按钮的 Click 事件所做的那样,但它不起作用。我如何获得它,所以当我在窗口上使用它时,它是必需的:
<MyControl:LabeledTextBox
TextBoxChange="Some_Event"
TextValue="{Binding SomethingOrOther}"
/>
它会正确触发并执行所需的功能
I have a customer usercontrol that is a labeled TextBox
(Border
wrapped about a Label
and a TextBox
with the TextBox
overlapping the label). I am finding few (working) examples on how to get the TextChanged
function to work when called from my UserControl.
Just the textbox snippet:
<TextBox
FontSize="{Binding Path=DefaultFontSize}"
Style="{StaticResource WatermarkTextBox}"
Padding="{Binding Path=TextPadding}"
Tag="{Binding Path=TextValue}"
/>
I have tried using RoutedEventHandler
like I did with my button's Click event, but it didn't work. How do I get it so when let's say I use on the window it is required:
<MyControl:LabeledTextBox
TextBoxChange="Some_Event"
TextValue="{Binding SomethingOrOther}"
/>
that it will fire off correctly and do the needed function
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这个问题实在是不清楚。您是否希望用户控件支持当
TextBox
中的文本更改时引发的TextChanged
事件?如果是这样,您需要在代码隐藏中实现它。首先,声明事件:
然后,将事件处理程序添加到
TextBox
:并在代码隐藏中:
This question's really unclear. Do you want your user control to support a
TextChanged
event that gets raised when the text in theTextBox
changes? If so, you need to implement it in the code-behind.First, declare the event:
Then, add an event handler to the
TextBox
:and in the code-behind:
如果您使用 MVVM(或者如果您的
TextValue
绑定绑定到您可以访问和编辑的内容),您可以将您想要执行的逻辑放在 setter 中。因此,假设您要绑定到属性
MyTextBoxValue
。在 XAML 中将绑定模式设置为两种方式,并在 setter 中放置逻辑或调用另一个方法。如果您希望每次键入时触发代码,请在 XAML 中设置
UpdateSourceTrigger=PropertyChanged
;如果您希望仅在文本输入“完成”时触发代码,请设置UpdateSourceTrigger=LostFocus
代码>.If you are using MVVM (Or if your
TextValue
binding is binding to something you can get to and edit) you can put the logic you want executed in the setter.So, lets say you are binding to a property
MyTextBoxValue
. Set the binding mode to two way in the XAML, and in the setter put the logic or call to another method.If you want the code to fire every time you type, set
UpdateSourceTrigger=PropertyChanged
in XAML, if you want the code to fire only when text entry is "done" setUpdateSourceTrigger=LostFocus
.