[WPF] How to bind to data when the DataContext is not inherited

Very poorPoorAverageGoodExcellent (26 votes) 
Loading ... Loading ...

The DataContext property in WPF is extremely handy, because it is automatically inherited by all children of the element where you assign it; therefore you don’t need to set it again on each element you want to bind. However, in some cases the DataContext is not accessible: it happens for elements that are not part of the visual or logical tree. It can be very difficult then to bind a property on those elements…

Let’s illustrate with a simple example: we want to display a list of products in a DataGrid. In the grid, we want to be able to show or hide the Price column, based on the value of a ShowPrice property exposed by the ViewModel. The obvious approach is to bind the Visibility of the column to the ShowPrice property:

<DataGridTextColumn Header="Price" Binding="{Binding Price}" IsReadOnly="False"
                    Visibility="{Binding ShowPrice,
                        Converter={StaticResource visibilityConverter}}"/>

Unfortunately, changing the value of ShowPrice has no effect, and the column is always visible… why? If we look at the Output window in Visual Studio, we notice the following line:

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=ShowPrice; DataItem=null; target element is ‘DataGridTextColumn’ (HashCode=32685253); target property is ‘Visibility’ (type ‘Visibility’)

The message is rather cryptic, but the meaning is actually quite simple: WPF doesn’t know which FrameworkElement to use to get the DataContext, because the column doesn’t belong to the visual or logical tree of the DataGrid.

We can try to tweak the binding to get the desired result, for instance by setting the RelativeSource to the DataGrid itself:

<DataGridTextColumn Header="Price" Binding="{Binding Price}" IsReadOnly="False"
                    Visibility="{Binding DataContext.ShowPrice,
                        Converter={StaticResource visibilityConverter},
                        RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}}"/>

Or we can add a CheckBox bound to ShowPrice, and try to bind the column visibility to the IsChecked property by specifying the element name:

<DataGridTextColumn Header="Price" Binding="{Binding Price}" IsReadOnly="False"
                    Visibility="{Binding IsChecked,
                        Converter={StaticResource visibilityConverter},
                        ElementName=chkShowPrice}"/>

But none of these workarounds seems to work, we always get the same result…

At this point, it seems that the only viable approach would be to change the column visibility in code-behind, which we usually prefer to avoid when using the MVVM pattern… But I’m not going to give up so soon, at least not while there are other options to consider ;)

The solution to our problem is actually quite simple, and takes advantage of the Freezable class. The primary purpose of this class is to define objects that have a modifiable and a read-only state, but the interesting feature in our case is that Freezable objects can inherit the DataContext even when they’re not in the visual or logical tree. I don’t know the exact mechanism that enables this behavior, but we’re going to take advantage of it to make our binding work…

The idea is to create a class (I called it BindingProxy for reasons that should become obvious very soon) that inherits Freezable and declares a Data dependency property:

    public class BindingProxy : Freezable
    {
        #region Overrides of Freezable

        protected override Freezable CreateInstanceCore()
        {
            return new BindingProxy();
        }

        #endregion

        public object Data
        {
            get { return (object)GetValue(DataProperty); }
            set { SetValue(DataProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Data.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty DataProperty =
            DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));
    }

We can then declare an instance of this class in the resources of the DataGrid, and bind the Data property to the current DataContext:

<DataGrid.Resources>
    <local:BindingProxy x:Key="proxy" Data="{Binding}" />
</DataGrid.Resources>

The last step is to specify this BindingProxy object (easily accessible with StaticResource) as the Source for the binding:

<DataGridTextColumn Header="Price" Binding="{Binding Price}" IsReadOnly="False"
                    Visibility="{Binding Data.ShowPrice,
                        Converter={StaticResource visibilityConverter},
                        Source={StaticResource proxy}}"/>

Note that the binding path has been prefixed with “Data”, since the path is now relative to the BindingProxy object.

The binding now works correctly, and the column is properly shown or hidden based on the ShowPrice property.

54 Comments

  1. Tundres says:

    Amazing, it worked like a charm!

    I was stucked with this problem for a while…thank you very much!

  2. Rohit Vats says:

    But suppose if i want to bind the Text property to some property in my DataContext and i want it to be two way binding. But with this StaticResource we can only bind it OneWay from Source to target. How two way binding can be achieved?

  3. Rohit Vats says:

    Oh i was trying to set it over the proxy binding. My bad. Thanks a lot for such a nice article..!!

  4. I was stuck for hours trying to get an Infragistics XamDataTree to behave nicely in a MVVM setting. The “nodes” in the tree behave just like the DatagridTextColumn in your example. I gave that BindingProxy a try and it worked right away. That saves me from having to write a lot of ugly code to manage the different context menus for each node types (and probably break MVVM a little in the process.) You”re a life saver! Very clever trick. Merci beaucoup!

    Thanks,
    Michel

  5. dewkid says:

    Wow – very elegant solution! I”ve been banging my head for hours with this problem, and none of the other solutions I found really solved it in XAML. This is a MUST for my MVVM project, and it works beautifully!!

    Thanks for posting this!

    Robin

  6. Thanks for the article, it saved me a lot of work because i was thinking to create one column at a time on the fly. And that was not looking good. However, I am stuck with a small problem with this solution, my .NET part of application works with this binding proxy but my silverlight application does not recognize Freezable obviously because its not using .NET framework. Do you have any idea who can I achieve same binding in a silverlight xaml view?

  7. Sankar says:

    This was a very useful post and it helps me lot in my work. Now we are porting our application to WinRT, while doing this i have found that the Freezable class was not found in WinRT. so please suggest a way to overcome this.
    Thanks,
    Sankar

    • Thomas Levesque says:

      Hi Sankar, I haven”t really got my hands on WinRT yet, so I don”t have an answer for that… sorry.

  8. Eddie Cosme says:

    Thanks so much! This is exactly what I was looking for.

  9. Basit says:

    Thanks a lot!

  10. Miro says:

    Thanks a lot, this really caused a lot of trouble till i found your solution

  11. GonzaloR says:

    Great solution for this cases

  12. Alireza says:

    Awesome, Thank you

  13. pappt says:

    I think this works too:
    DataContext=”{Binding RelativeSource={RelativeSource AncestorType=GridViewColumnHeader}, Path=DataContext}” Binding=”{Binding Price}”

    • Thomas Levesque says:

      No it doesn”t, because RelativeSource uses the visual tree, and the DataGridColumn is not part of the visual tree…

  14. Ket says:

    Is there any difference while using this trick with Silverlight?
    Also I am using older version of .NET and cannot find Freezable class. Any idea?

    Thanks !!

    • Thomas Levesque says:

      Hi Ket,
      The .NET framework itself has the Freezable class since the first version of WPF (.NET 3.0). However Silverlight only uses a subset of the .NET framework, and this class isn”t part of it. I don”t know if there”s another way to make it work in Silverlight…

  15. Claudia says:

    thank you very much! :)

  16. Arena says:

    Hi,
    It was very nice, but what i need is bind width property and when i resize a column in grid then i want to update the property in viewmodel…its not working..can you help….?

    • Thomas Levesque says:

      Hi Arena,
      What”s causing you trouble exactly? You just need to do a two-way binding on your ViewModel property (Mode=TwoWay)

  17. Arena says:

    I had tried that but actual problem is when i resize column width on UI by mouse then width property in viewmodel is not getting updated…i dont know why…i am new to WPF…so please help me….

    • Thomas Levesque says:

      Hi Arena,
      I don”t know why it isn”t working for you, but it doesn”t seem related to my blog post in any way… You should probably ask your question on Stack Overflow or some other forum.

  18. Arena says:

    Ok…thank you Thomas…:)

  19. lymber says:

    Hey thanks for the article, solved my issue when trying to bind to the visiblity and isReadOnly property of the datagrid column!

  20. Anders says:

    Thanks Thomas, solved by column MVVM visibility problem

  21. Mark Siminski says:

    Thank you, thank you, thank you! Like everyone else you helped said, this has helped me tremedously! You sir, are a steely eyes rocket man!

  22. Alex says:

    Thanks… It realy works !

  23. Rakesh Bisht says:

    Hello Thomas,

    Thanks for this solution.
    I had a requirement for binding the string format for a Infragistics XamGrid TextColumn and it was not working the normal way.

    I had multiple string formats and one string format was required to applied depending on user input.
    But this solution helped me in working that out.

    Thanks again.

  24. Kyle says:

    Thomas,

    Nice solution!!! Though I’m having trouble getting it to work in concert with a ListBox ItemContainerStyle. In my scenario I’m setting a RotateTransform on the ListBoxItem using a Setter in my style. I want the Angle of the transform to bound to the ViewModel set in the DataContext of the ListBoxItem. Sadly, I get that pesky binding error so I tried your solution. Strangely enough, it is working as expected, e.g. it does see the Angle on my ViewModel.

    In my scenario I need the binding proxy on each ListBoxItem so that it gets the appropriate binding when referenced by the RotateTransform, but I can’t seem to find the best place to place the proxy and get it recognized either syntactically or at runtime when I do have the correct syntax.

    Thanks

    • Thomas Levesque says:

      Hi Kyle,

      Good question… actually I’m surprised that it doesn’t work without the BindingProxy.

      You could try to put the BindingProxy in the Style’s resources, with x:Shared=”True” (just an idea, not sure it would work)

      • Christoph says:

        Thomas,

        I have the same issue: BindingProxy doesn’t work in a Style. x:Shared=”true” does not help :-(
        Any idea?

  25. Ram says:

    I have a Visibility property in my ViewModel and based on which i need to display/hide the Column. This scenario works for me for the first time, but when i change the Visibility property through code, it does not reflect back on UI. Please help.

  26. Narendra M. says:

    Astonishing – only a real WPF expert could have done this. Thank you so much.

  27. Itamar says:

    Hi.
    1. That’s some brilliant solution. You rock !
    2. I’m trying to create the _DataGridTextColumn_ on the code behind (because every column needs that:
    _textColumn.Binding = new Binding(“Cell[" + intColIndex.ToString() + "].Value”).

    Eventually, your solution works on XAML, but not on the code behind :-(

    Probably because I have a mistake in translating this XAML to code…

    Any idea will be appreciated. Thank you.

    • Thomas Levesque says:

      Hi,

      I don’t really understand what your problem is… You don’t need the BindingProxy to bind to a member of an item; DataGridColumn.Binding is relative to the item, so it should work directly.

  28. Muhammad Alaa says:

    Great article
    Thank you, thank you, thank you

  29. Tim Orr says:

    Extremely valuable solution. Thank you!

  30. Adnan Khan says:

    Perfect!

  31. A little gem for my toolbox. Thank you. :)

  32. J. Dunlavy says:

    Excellent blog entry! I was encountering this hang-up when trying to do the exact same thing: hide / show column based on a viewmodel property.

    My hair was falling out.

    It’s also rather great that you mentioned those attempts to “tweak” the binding. I did both of those in XAML before coming across this blog post. And I already had a code-behind workaround implemented, which I happily discarded in favor of the professional solution you presented here.

    Thanks!

  33. Stijn says:

    Excellent post! Works perfectly :-)

  34. Andrew Fernie says:

    Can’t get this working. I take it this is supposed to change the visibility of the entire column and not just the visibility of a particular cell in that column on a given row?

    In your example, is ‘ShowPrice’ a property of the same object (i.e. order item) as the ‘Price’ property? Or is it a property of some parent object (i.e. order)?

    What I am trying to achieve in my application is to show/hide an OPC quality column in a datagrid containing OPC tags and their associated values. I’d like to bind the visibility of the quality column to the ‘connected’ property of my OPC client object.

    Would be really helpful to be able to download your full example if that’s available.

    Thanks

    • Thomas Levesque says:

      Hi Andrew,

      In my example, ShowPrice is a property of a parent object (typically the ViewModel for the whole view).

      Here’s a full example of the scenario I described:
      http://1drv.ms/1nD9lfo

      • Andrew Fernie says:

        Thomas,

        Thanks for posting a link to the full example. Got my application working now exactly as I had wanted thanks to your code.

        Thanks for you help!

  35. Jared says:

    You, sir, are a god.

  36. Vishal says:

    I know that this post is very Old, but I think it will be good to ask you instead of asking a new question. I have tried the above mentioned code sample. But It doesn’t seem to work for me. So, I created a Sample application. In that sample application also I cannot get it to work. If you can answer this, then please have a look at the sample project here : https://drive.google.com/file/d/0B5WyqSALui0bWGdJRzhaMmFEMms/edit?usp=sharing

    • Thomas Levesque says:

      Hi Vishal,

      I’m not sure what’s going on… it looks like it should work, but for some reason the Path on the Visibility binding is reset, and I have no idea why.
      Anyway, the typical usage of this class is to provide a proxy to a datacontext; in your sample app, you don’t have a datacontext at all… Check out this sample project for a complete example: http://1drv.ms/1nD9lfo

      • Vishal says:

        Ok, I have looked at your sample. There you are creating a property and made that property the middle man instead of binding checkbox’s IsChecked Property to the dataGridColumn’s Visibility directly. You have looked at my sample project. But my real project is much different than that sample. There I am binding a DataGridColumn’s visibility to TextBlock’s Visibility. I cannot create a property to bind to the TextBlock’s Visibility as it’s visibility depends on many other control’s input, in short I have used Multi-Binding on the Visibility Property of that textBlock.

        Can you give some suggestions?

        And thanks for taking time and explaining such a great post.

        • Vishal says:

          Sorry for the above comment. I just forgot to specify Path = Data in DataGridTemplateColumn’s Visibility.

3 Trackbacks

Leave a comment

css.php