abelenky
abelenky

Reputation: 64682

Cannot access an XAML class-instance from code

I've created an class which will be the DataContext for my app, and instantiated it via XAML:

<Window x:Class="MyApp.UI.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:myDataModel="clr-namespace:MyApp.MyDataModel"
    Title="MainWindow">
<Window.Resources>
    <myDataModel:MyDataClass x:Name="the_DataModel" x:Key="a_DataModel"/>
</Window.Resources>

I want to act on this object in the constructor of my Window:

public MainWindow()
{
    InitializeComponent();

    the_DataModel.LoadFromFile(); // One of these *should* work!
    a_DataModel.LoadFromFile();
}

However it seems that neither name (the_DataModel, nor a_DataModel) is a member of the Window class. When I type this., and use auto-complete, I cannot find anything that resembles the object I created in XAML.

How can I create an instance of a class in XAML, and access it in code?

Upvotes: 1

Views: 247

Answers (1)

Rohit Vats
Rohit Vats

Reputation: 81253

Since you have added it as a resource in window resources, you can get it from Resource collection by indexing with resource key.

MyDataClass dataModel = (MyDataClass)Resources["a_DataModel"];
dataModel.LoadFromFile();

Upvotes: 2

Related Questions