简体   繁体   中英

Get DataContext From XAML

I deleted the CodeBehind of my MainWindow.xaml, cause I'm doing a small project where I literally must do that.

So I'm creating an instance of my ViewModel in this way over xaml:

<Grid.DataContext>
    <lib:StartPageViewModel />
</Grid.DataContext>

Well now, I need this DataContext in my Code (StartPageViewModel), as I want to open an other solution (For more Informations take a look here ).

Any Ideas, on how I can get this DataContext?

At least I solved the problem. Actually I didn't really need to use the DataContext for this:

    public static DTE2 GetDTE(DataContext dataContext)
    {
        ICustomTypeDescriptor typeDescriptor = dataContext as ICustomTypeDescriptor;
        Debug.Assert(typeDescriptor != null, "Could not get ICustomTypeDescriptor from dataContext. Was the Start Page tool window DataContext overwritten?");
        PropertyDescriptorCollection propertyCollection = typeDescriptor.GetProperties();
        return propertyCollection.Find("DTE", false).GetValue(dataContext) as DTE2;
    }

I changed the code to the following, it works now perfectly, I can open Solutions without using the DataContext:

    public static DTE2 GetDTE()
    {
        return (DTE2)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE");
    }

A ViewModel shouldn't know anything about the View.

So when applying 'proper' MVVM, you shouldn't be trying to get to the DataContext from within the ViewModel.

The code of the StartPageViewModel IS part of the object that is put in the DataContext. This means that you can access the object by using this in the code of the ViewModel.

If you are looking for the Grid (or even higher up the VisualTree) you could pass it using a property in the Xaml:

<Grid Name="MyGrid">
    <Grid.DataContext>
        <lib:StartPageViewModel MyParent={Binding ElementName=MyGrid} />
    </Grid.DataContext>
</Grid>

Still, if you do that, you are adding knowledge about the View to the ViewModel.

I've never declared a viewmodel in a XAML file, but have you tried:

viewName.DataContext as ViewModelType;

BTW, deleting the code-behind is usually a good practice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM