Matthias Herrmann Matthias Herrmann - 10 months ago 55
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


What I tried:

I wrote this xaml Code:

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

And have added this Piece of Code:

private RelayCommand _loadedVisualizerCommand;
public RelayCommand LoadedVisualizer
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


public PreviewTile PreviewTile { get; set; }


public MainPage()


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 Source

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 );


    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.