user1531186
user1531186

Reputation: 343

Reference the View from ViewModel while using DataTemplate for the ViewModel

i'm using a DataTemplate to provide the association of View to ViewModel, for example:

<DataTemplate DataType="{x:Type viewModels:SomeViewModel}">
    <views:SomeView />
</DataTemplate>

now i need to reference the View somehow in my ViewModel, so i could reference some control directly by its name. Is there anyway to do that?

thanks for your help

Upvotes: 0

Views: 318

Answers (1)

Lukas Kubis
Lukas Kubis

Reputation: 929

Maybe this is what you're looking for:

public partial class SomeView : UserControl
{
    public SomeView()
    {
        InitializeComponent();
        this.Loaded += View_Loaded;
    }

    void SomeView_Loaded(object sender, RoutedEventArgs e)
    {
        var someViewModel = (SomeViewModel)this.DataContext;
        someViewModel.View = this;
    }
}

Upvotes: 1

Related Questions