Matthias Herrmann Matthias Herrmann - 2 months ago 14
C# Question

Bind Event To Command And Get Refference To UI Element

What I want to achieve: I want a Command to be triggered when the element has been loaded and I want to get a Refference to this element, so I can Access it in the

MainViewModel.cs
.

What I tried:

I wrote this xaml Code:

<visualizer:PreviewTile DisplayName="Share Tile" TileSize="Wide" Background="Red" IsAnimationEnabled="True" x:Name="P">
<interactivity:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="Loaded">
<core:InvokeCommandAction Command="{Binding LoadedVisualizer}"></core:InvokeCommandAction>
</core:EventTriggerBehavior>
</interactivity:Interaction.Behaviors>
</visualizer:PreviewTile>


And have added this Piece of Code:

private RelayCommand _loadedVisualizerCommand;
public RelayCommand LoadedVisualizer
{
get
{
return _loadedVisualizerCommand
?? (_loadedVisualizerCommand = new RelayCommand(
async () =>
{
await new MessageDialog("Loaded", "Some Content").ShowAsync();
}));
}
}


But the Method doesn't get called when the Event Loaded is getting fired.

So I tried this to get a Refference to the Control, but it is throwing a
NullRefference
exception:

In
MainViewModel
:

public PreviewTile PreviewTile { get; set; }


In
MainPage.xaml.cs
:

public MainPage()
{

InitializeComponent();

Loaded += (s, e) =>
{
Vm.PreviewTile = P;
};

}


Despite there are some articles and questions (some unanswered) about using Events in mvvm light I can't figure out how I can get this working.

Answer

The only reason I can see for this is that the Page's DataContext is not correctly set. To use the MainViewModel on the page, you have to add it in your ViewModelLocator class:

public class ViewModelLocator
{
    static ViewModelLocator()
    {
        ServiceLocator.SetLocatorProvider( () => SimpleIoc.Default );

        SimpleIoc.Default.Register<MainViewModel>();
    }

    public MainViewModel Main => ServiceLocator.Current.GetInstance<MainViewModel>();
}

And then use it on your MainPage:

<Page ...
DataContext="{Binding Source={StaticResource Locator}, Path=Main}">

Now the EventTriggerBehavior should work as expected.

I have put a sample project on my GitHub for you to check out.