问题
I'm making use of the MVVM Light ViewModelLocator. I have a class called GlobalViewModelLocator which is hooked up in the resources in the App.Xaml. This class has a static property called Main which returns an instance of the MainViewModel.
Then in the MainView.Xaml, I set the datacontext of the usercontrol to bind to the path of this MainViewModel. This works fine - I put a breakpoint on the MainViewModel constructor and it is being hit once. However, all the properties in the ViewModel which are set as a result of event triggers on controls within the MainViewModel are being hit three times. Does anyone know why this could be happening?
Here is a sample of the code in the MainView.Xaml:
<UserControl.DataContext>
<Binding Path="Main" Source="{StaticResource Locator}"/>
</UserControl.DataContext>
<Grid x:Name="LayoutRoot" Background="#FF292929">
...
<MediaElement Stretch="Fill" AutoPlay="False" Name="mediaElement">
<MediaElement.Style>
<Style TargetType="MediaElement">
<Setter Property="OpacityMask" Value="Black"/>
</Style>
</MediaElement.Style>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding MediaOpenedCommand}" CommandParameter="{Binding ElementName=mediaElement, Mode=OneWay}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</MediaElement>
...
In this case, the MediaOpenedCommand is being hit three times. Any idea why?
回答1:
I found the reason that it is getting hit three times is because that particular view is being referenced three times from within different XAML pages.
Thanks
来源:https://stackoverflow.com/questions/3829418/mvvm-light-using-viewmodellocator-properties-hit-multiple-times