开发者

MVVM- Is there a way that I can get and set a textbox's text without using databinding?

开发者 https://www.devze.com 2022-12-27 11:51 出处:网络
I need to be able to get and set the textbox\'s text, but I don开发者_开发知识库\'t want every single change in the textbox\'s text to update a string in my viewmodel. It seems to me that binding a st

I need to be able to get and set the textbox's text, but I don开发者_开发知识库't want every single change in the textbox's text to update a string in my viewmodel. It seems to me that binding a string to the textbox's text property would be nearly as inefficient as updating a string on a textbox's textchanged event or am I wrong?


The default UpdateSourceTrigger for bindings to TextBox.Text is LostFocus, which means that the string in your viewmodel is only updated when the TextBox is left.

Of course, if you do something like this

<TextBox Text="{Binding Path=ItemName, UpdateSourceTrigger=PropertyChanged}" />

then your string will be updated every time something changes in the text box. So, yes, it would be "nearly as inefficient as updating a string on a textbox's textchanged event".

Still, I don't see a real-world problem here: Even if you have a very fast typing user, updating a string in memory is not an operation that takes a terrible amount of time. In fact, processing the user input by the TextBox itself (showing the characters typed, scrolling the text to the left if the end of the box is reached, etc.) also needs quite a bit of processing, so I don't think updating your string creates such an unreasonable additional burden.


I would think it really depends what you define as efficient. To me, being able to declare a two-way binding declaratively on the XAML level is a lot more efficient than handling the text changed event and attaching myself to the property changed of a view model and copying stuff back and forth.

Why would I do that?

Apart from that, the default binding behaviour is on focus lost...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号