Search code examples
c#wpfdata-bindingxamldatacontext

Can I reassign from code an object declared as a resource in XAML?


I have a class for my data, MyData, and I'm accessing it in my gui by data binding.

I decided to set the DataContext of the main panel in my window to an instance of this object so I could bind my various controls to it's members. So I could easily reference it in my XAML, I created an instance of MyData in Window.Resources like so:

<local:MyData x:Key="myDataInstance"/>

Then I get a reference of this for my code because I need it there sometimes too.

MyData myDataInstance;

public MainWindow()
{
    InitializeComponent();
    myDataInstance = (MyData)FindResource("myDataInstance");
}

This works well, but I also can load another instance of MyData by deserializing it from file.

myDataInstance = (myData)serializer.Deserialize(fileStream);

I thought I could simply reassign myDataInstance in the code like this, but that doesn't seem to be working since my gui doesn't change to reflect the new data. I think reassigning is breaking the link between the main panel's DataContext and myDataInstance.

  1. Is it possible to reassign an object declared in xaml as I have?
  2. From XAML, is it possible to access members declared only in the code (the opposite of FindResource())?
  3. If so, how?

Thanks. (btw, Of course I can use other methods to easily solve this problem, but I'm also just interested in the answer to this question.)


Solution

  • You could try

    public class MainWindow {
    
    ...
      void UpdateResource()
      {
         myDataInstance = (myData)serializer.Deserialize(fileStream);
         this.Resources["myDataInstance"] = myDataInstance;
      }   
    }
    

    then make sure that where ever you reference your resource you use a DynamicResource reference rather than a StaticResource reference.

    Adding items to Resource dictionaries and using DynamicResource references is, as far as I know, the only way of making things in code available to XAML.