WPF DataContext Bindings on Multiple Pages

Michael 41 Reputation points

I have an application that has one window and a dozen pages. I have a class of bindable properties I want to use for bindings on several pages. I also need to access them often in the code behind.

I am not totally satisfied with my current solution. I instantiate the class of bindables as public static. I set up another routine as public static that declares the bindables as datacontext to the window and pages I need. This way they all share the same instance.

public class dcx   // DataContext, bindable parameters
    public static Bindables myBindables = new Bindables();

    public static void InitializeDataContext()
        win.Main.DataContext = myBindables;
        pages.page1.DataContext = myBindables;
        pages.page2.DataContext = myBindables;
        pages.page3.DataContext = myBindables;

One of the drawbacks to this is that at design time none of the parameters are available. It makes design much more difficult. I guess I could declare the datacontext with d: and then at runtime it would get overridden.

It just all seems like there should be a better way.

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,697 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Michael 41 Reputation points

    By default every XAML file has line near the beginning: mc:Ignorable="d". Things proceeded d: are used by the rendering engine or compiler darning design time. During the compile to an executable they are ignored. When you right click a properties of a control and select Create Data Binding you get a dialog. When you do datacontext in C# there is no reference to whatever is in datacontext. When you do it the way that you did you will see the properties of what is in datacontext in the dialog. Hence, the dilemma.

    The problem of doing what you did is that it instantiates StudentViewModel. Every page you do this on will look at a different instance. What I did was create a single instance. I pointed all datacontext binding to look at the same instance.

    Note, I have not tried using d: for datacontext. I have used d: for other things. Every thing I have read says it should work for datacontext also.

  2. Michael 41 Reputation points

    The letter is not as important as mc:Ignorable. I tried it and it does not work. I put in the DataContext lines in for development. I comment them out when a run. Kind of sledge hammer but it works.

    Back to the original question. What is the best way to do DataContext Bindings on Multiple Pages?