Databinding to a method in WPF
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:
- User types a new
Filename
into a boundTextBox
and presses TAB. - The
TextBox
loses focus. - Because the
Binding
's mode isTwoWay
, and it's using the default behavior of updating the source when the target loses focus, that's what it does. - The
Binding
updates the source by calling theFilename
setter. - The
Filename
setter raisesPropertyChanged
. - The
Binding
handlesPropertyChanged
, looks at its argument, and sees that theExtension
property has changed. - The
Binding
calls theExtension
property's getter. - The
Extension
property's getter calls the method to determine the extension forFilename
, and returns it to theBinding
. - The
Binding
updates its targetTextBox
with the new value ofExtension
.
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.
Looks like you need to get an understanding of MVVM , check this classic article http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
Databinding requires the NotifyPropertyChanged
event to be called when the source is updated. In this case, you'd want to wrap this function call in a get/set like so:
public class FileWrapper: System.ComponentModel.INotifyPropertyChanged{
private string m_filename;
public string FileExtension{
get{ return GetFileExtension(FileName);}
}
public string FileName{
get{ return m_filename;}
set{ m_filename = value; OnPropertyChanged("FileName"); OnPropertyChanged( "FileExtension");
}
public string GetFileExtension( string filename){
//implementation
}
public event System.ComponentModel.NotifyPropertyChangedEvent PropertyChanged = (a,b)=>{};
protected void OnPropertyChanged(string property){
PropertyChanged( this, new System.ComponentModel.PropertyChangedEventArgs( property ));
}
}