The case is: I have a control's event that I want my ViewModel to react on. Currently I'm doing this by executing a command of invisible button like in the example below.
In View.xaml:
<Control x:Name="SearchResultGrid" ... DataRefreshed="SearchResultRefreshed" />
<Button x:Name="SearchResultRefreshedButton" Visibility="Collapsed" Command="{Binding SearchResultRefreshedCommand}" />
In View.xaml.cs:
private void SearchResultRefreshed(object sender, EventArgs e)
{
if (SearchResultRefreshedButton.Command != null)
{
SearchResultRefreshedButton.Command.Execute(SearchResultGrid.ResultRowCount);
}
}
This works good, but it looks like a hack to me. I'm wondering if there is better (standard) way of doing this? I could not find any examples and this is what I "invented" myself.
You should add a dependency property
DataRefreshed
to your control in order to bind on ithere an example how you can do it
Then you can manipulate your property like any other WPF property for example
SearchResultRefreshed
which is defined in your ViewModeltake a look at the following tutorial to understand more
dependecyproperty and attachedproperty
Personally I've never had a need to use an attached property to deal with a control's event. In your example, of a control wanting to know when the 'SearchResultRefreshed' and then informing the ViewModel through the hidden control ... why doesn't the ViewModel already know that the results have been refreshed?
If the results are coming from the ViewModel in the first place, and binding is used to display them within your control, then the knowledge that the search results have been refreshed should be driven by your ViewModel - not your view.
In only a few cases have I found a need to break away from ICommands and data-binding.
Using MVVM, the general way to handle events is to simply wrap them in Attached Properties, or use Attached Events. Here is an example using the
PreviewKeyDown
event in an Attached Property:Note that it is just as easy (and better too) to use an
ICommand
instead of the actualKeyEventArgs
object which shouldn't really be in the view model. Just create an Attached Property of typeICommand
and call that from thisTextBox_PreviewKeyDown
handler instead:Either way, it would be used something like this:
Or if you used the preferred
ICommand
method: