Register on specific changed property in MVVM Light on WP7
I've created a view with a listbox on it which shows a collection of Cars on it. If a user clicks on a specific car, 开发者_StackOverflow中文版he needs to be sent to a different view with some detailed information on it.
The binding properties are normal MVVM Light properties (with RaisePropertyChanged
and all).
Some code snippets:
<ListBox ItemsSource="{Binding Cars}" SelectedItem="{Binding SelectedCar, Mode=TwoWay}">
While developing this application I've discovered I can register for property changed events using the Messenger object of MVVM Light, like so:
Messenger.Default.Register<PropertyChangedMessage<Car>>(this, (action) =>
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
DoViewDetail();
});
});
But if I'm correct, this will register for every changed Car in the whole application. It's probably possible to do something with the RaisePropertyChanged
or Register
so you can target a specific property, but I can't find seem to find it.
Anyone here got a clue or heads up? In short: I want to register on a specific property, not a specific object in my MVVM Light application.
I think one alternative is to create a custom "message" to use only in connection with the desired functionality. For example declare a CarSelectedMessage
and then instead of using the default broadcasting of PropertyChangedMessage<Car>
, create and send the custom message from the view model:
public Car SelectedCar {
get { return _selectedCar; }
set {
_selectedCar = value;
RaisePropertyChanged("SelectedCar");
var msg = new CarSelectedMessage(value);
Messenger.Default.Send(msg);
}
}
On navigation in general
For implementing navigation in the application, I followed this blog post to make it simple to issue navigation requests from view models. I think it had to be updated a little for the latest version of MVVM Light though, see my version below.
New NavigationRequest
class to be used as the message:
public class NavigationRequest
{
public NavigationRequest(Uri uri)
{
DestinationAddress = uri;
}
public Uri DestinationAddress
{
get;
private set;
}
}
Register for requests in the constructor of the application's main view:
Messenger.Default.Register<NavigationRequest>(this,
(request) => DispatcherHelper.CheckBeginInvokeOnUI(
() => NavigationService.Navigate(request.DestinationAddress)));
Finally for calling navigation from a view model
var uri = new Uri("/MyPage.xaml", UriKind.Relative);
Messenger.Default.Send(new NavigationRequest(uri));
Hope this helps,
精彩评论