Databinding to a method in WPF

前端 未结 5 1203
失恋的感觉
失恋的感觉 2021-02-13 13:49

I am having trouble databinding a TextBox.Text property to a object\'s method. The idea is allowing the user to write in a TextBox a file name and then

5条回答
  •  忘了有多久
    2021-02-13 14:23

    While it's possible to use Binding to call a method and get its return value, it's not straightforward. It's much simpler to bind to properties, and to use the combination of binding and change notification to get the result you're looking for.

    Create a class with two properties, Filename and Extension. Filename is just a read/write string property. Extension is a read-only string property whose getter calls the method that you're trying to call.

    Now make that class implement INotifyPropertyChanged, because if a property can change in code, it needs a way of telling the binding that it has done so. Make the setter of the Filename property notify bindings that the Extension property has changed.

    Add a Binding to a TextBox that binds to the Filename property using the TwoWay mode. Add a Binding to a TextBox that binds to Extension using the default OneWay mode.

    The sequence of events is:

    1. User types a new Filename into a bound TextBox and presses TAB.
    2. The TextBox loses focus.
    3. Because the Binding's mode is TwoWay, and it's using the default behavior of updating the source when the target loses focus, that's what it does.
    4. The Binding updates the source by calling the Filename setter.
    5. The Filename setter raises PropertyChanged.
    6. The Binding handles PropertyChanged, looks at its argument, and sees that the Extension property has changed.
    7. The Binding calls the Extension property's getter.
    8. The Extension property's getter calls the method to determine the extension for Filename, and returns it to the Binding.
    9. The Binding updates its target TextBox with the new value of Extension.

    This is the core concept underlying data binding and the MVVM pattern. Once you understand it, it becomes second nature, and WPF development becomes about ten million times easier.

提交回复
热议问题