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

Very poorPoorAverageGoodExcellent (42 votes) 

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},

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();


        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:

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

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.


  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!


    • Ten-Seng Guh says:

      Michel I was in the exact same boat, stuck for hours, on the verge of breaking MVVM and write nasty handlers all over the place. Thank goodness for this solution!

  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!


  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?

    • Sorry, I don”t have any experience with Silverlight, so I don”t know how to tackle this problem in SL…

      • Jerre says:

        Seems to work fine in SL like this:

            public class BindingProxy : Control
                public static readonly DependencyProperty DataProperty = DependencyProperty.Register( "Data", typeof(object), typeof(BindingProxy), null);
                public object Data
                    get { return (object)GetValue(DataProperty); }
                    set { SetValue(DataProperty, (object)value); }
  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.

    • 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:

    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:


    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.


    • 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:


        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:

    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:


      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:


  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.


  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.


    • 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:

      • Andrew Fernie says:


        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.

  37. Mafaz says:

    Hey..Thank you very much. That was very elaborative and far much easier to track the problem.

  38. Richard says:

    Hi Thomas,

    Thanks for taking the time to post this, you helped me solve a particularlly tricky problem. I have successfully used your code to implement an MVVM approach for a Treeview with a context menu whose ItemsSource is defined on the Viewmodel bound to the treeview but I am having difficulties implementing this with a DataGrid.

    My DataGrid has binding to an ObservableCollection of objects, the grid columns specify which property of the objects to bind to and this works correctly.

    I have a property on the object that is an Observable collection of ContextMenu items, which is then bound to the itemsSource of the contextMenu definited on the DataGrid. I am using the same approach for this as with the Treeview that works.

    My problem is that when I attempt to set up a binding proxy to the DataGrid’s datacontext, it seems to be hooking up to the full observable collection that is bound to the ItemsSource of the datagrid. As a result I get a binding error when I bind the context menu itemssource to the menu items property of each object.

    Do you know if it’s possible to hook up an individual row’s datacontext to the binding proxy to then use an individual item as the itemssource for the context menu, where the binding would work correctly?



    • Thomas Levesque says:

      Hi Richard,

      It’s hard to tell what the problem is without seeing your code… Could you post it to Gist?

  39. Li Xu says:

    Thanks for the post. It is very useful to me.

  40. Bipin says:

    Thanks, quite good example instead of using framework element.

  41. Jane says:


    I tried your sample but found it doesn’t work in the following code:

    It works while I use multibinding on MenuItem.Header.

    And if I bind the itemssource in this way:

    it works,too.

    I don’t know why…T^T

    Please give me some help..Thank you very much.

  42. Tjak says:

    Hello Thomas,
    thanks a lot for sharing your solution. I just received this much-feared error message and was able to defeat it using your code.

  43. Luis Murillo says:

    Thanks Thomas! :)

  44. Ponkarthikeyan says:

    Thanks a lot for sharing the solution. The Freezable approach works.

  45. Thank you for this! You just saved me after 4 hours of hair pulling and swearing. This is great!

  46. mehmet says:

    thank you

  47. A simpler solution is to use a DataGridTemplateColumn.

    • Thomas Levesque says:

      How does that solve the problem? The DataContext in a cell of a DataGridTemplateColumn is the one of the current item, not the one of the DataGrid itself. How does it let you control whether the column is visible or not?

  48. Galina Ganeva says:

    That’s really great. It is mentioned nothing in the MSDN documentation about this interesting feature for the DataContext inheritance of Freeze objects. How did you reached to this conclusion?

  49. Gayatri says:

    Great solution..trying to do this since last two days..

  50. Hi,

    The DataGridTemplateColumn along with a MultiBinding can be used to solve this. The value converter needs to implement the IMultiValueConverter interface.

  51. Bùi Lương Trường says:

    Hi Thomas Levesque!
    Can you help me with binding.
    I have a binding in code like:

    *TextBlock Visibility=”{Binding Source={StaticResource DevTechResources}, Path=Path1.Path2.PropertyName, Converter={StaticResource AdminToVisibleConverter}}” /*

    if “Path2” is not null. My converter work perfectly.
    But if “Path2” is null. My converter doesn’t occurs.
    How can i fix this?

    • Thomas Levesque says:

      The converter is only called after the binding successfully gets a value from the source. If Path2 is null, it can’t access Path2.PropertyName, so it has nothing to convert. You can use TargetNullValue or FallbackValue to cover this case and specify the value to use in this case.

    • Bùi Lương Trường says:

      Thank Thomas!
      Can you give me some simple example how about TargetNulValue and FallbackValue work?

    • Bùi Lương Trường says:

      Thank Thomas!
      I fought out some example about TargetNullValue and FallbackValue.
      TargetNullValue and FallbackValue ignore Converter and get directly value

  52. shola says:

    I came across your BindingProxy from another source and have found it quite useful. However, I have an issue is that while it works well during runtime, it does not work within the IDE designer.

    I have the following in my Window.Resources (for demo, BrushProvider is a string)
    BindingProxy x:Key=”DataProxy” Data=”{Binding BrushProvider}”

    and use the following within a DataTemplate in a DataGridTemplateColumn
    TextBlock Text=”{Binding Path=Data, Source={StaticResource DataProxy}}”

    It ignores the binding at design time but works when I run it.

    I have posted sample code at http://stackoverflow.com/questions/28365996/bindingproxy-is-not-working-at-design-time

    Any ideas?

    • Thomas Levesque says:

      Hi Shola,
      I don’t know if it can work in the designer… I just tried with the example from the article, and I can confirm the problem. I suspect that Freezable doesn’t work in the usual way at design time, and there isn’t much we can do about it…

      • Shola says:

        Thanks Thomas for replying, That is what I thought.

        One workaround I found is to use a collapsed ContentControl instead and bind using ElementName and Path=Content. That works with the Microsoft DataGrid at design-time but not for some other third-party Grids.

        BindingProxy does work (at runtime) for all cases I have used it with, so it is very useful to have in my library.

  53. Jeff says:

    Just use this:

    ItemsSource=”{Binding}” IsSynchronizedWithCurrentItem=”true”


    • Thomas Levesque says:

      How does it solve the problem? It just makes the currently selected item match the ICollectionView.CurrentItem; it does nothing to the DataContext of the column.

  54. Gayatri says:

    Hi I am setting the visibilty of DataGridTemplateColumn as you mentioned above but I change the visibilty runtime in model on click event but its not reflecting in my grid..I tried using NotifyOnSourceUpdated, UpdateSourceTrigger on data of BindingProxy..didn’t work..Please help..

  55. Gayatri says:

    this columns datatemplate has button. On click event of this button I am changing the value of IsEditVisible this property
    is in my collection which is bound to datagrid.
    it is unable to bind changed values or its not calling my EditVisibiltyConverter

    • Thomas Levesque says:

      In this case you shouldn’t change the column’s visibility, but the button’s visibility in the template

  56. Guillaume says:

    Hi Thomas,

    Great post but as a more basic question : why ? I mean, the first two solutions proposed seem to be enough, but why does the binding not work ? Why do we have to use a proxy for this ?

    • Thomas Levesque says:

      Hi Guillaume,
      The proposed workarounds don’t work for the same reason the initial “normal binding” approach doesn’t work: the DataGridColumn isn’t part of the visual tree, so RelativeSource and ElementName don’t work, because they don’t have a point of reference.

  57. Andy says:

    Been trying (unsuccessfully) to bind to a DataGridTextColumn header for what feels like an eternity – your solution came to my rescue :-) Thank you for the post.

  58. Jérôme says:

    Merci, cette solution est en effet très simple et élégante !

  59. John Byerly says:

    After tearing my hair out for a couple of hours, I did a web search and hit this site via Stack Overflow.


    My problem was with a ContextMenu, which I knew did not inherit the DataContext, but I couldn’t figure out a way to make it work. Your solution worked out of the box. Thanks!

  60. Thanks a bunch m8.. Been beating my head around this for hours. No System Data Error here during debugging which made things ever worse lol!

    Thanks for sharing!

  61. mehmet says:

    best tip ever

  62. MarkF says:

    Yep, great tip. I was having this problem trying to bind values in a RenderTransform TransformGroup, solved it nicely. Thanks!

  63. Mark W says:

    thanks, worked like a charm with a custom DP and ValidationRule that has a property of that custom DP type (for use when comparing one bound value to another during validation)

  64. Derek says:


    I’m new to xaml and C# coming from C++… can you clarify the ShowPrice property?

    Presumably the ViewModel class has a public ShowPrice member or function. But how is ShowPrice then called relatvie to Data? What is the relationship between the ViewModel class and the BindingProxy class? Does the view model class need to inherit BindingProxy?


    • Thomas Levesque says:


      ShowPrice is a normal property with change notification on the ViewModel. The BindingProxy is used to access the ViewModel from the DataGridTextColumn, where it is normally not available. There is no relation between the ViewModel and the BindingProxy class, you don’t need to inherit.

      • Derek says:

        In your example, should I also expect Products.Name and Products.Price to update in the UI when they are changed in .cs code?

        This would be nice for UI’s with many fields, as I have it now it looks like I would need a custom set with an OnPropertyChanged call for each field.

        • Thomas Levesque says:

          The UI will be updated if the properties raise PropertyChanged notifications. I didn’t mention it in the article because it’s not relevant to the BindingProxy trick.

  65. Taj says:

    It solved my problem. Thank you very much.

  66. Jamie says:

    I’ve been using this technique, but I’ve run into an issue with it where it is generating the following error:

    Internal error: internal WPF code tried to reactivate a BindingExpression that was already marked as detached.

    If I remove this binding the error goes away.

    Any ideas what might be going on?

  67. Jhony says:

    I am trying to use your solution for my requirement. Seems i am missing out something here that it does not work or is not intended to be used like this..Could you please guide.

    This is the template for my GridViewItemCellTemplate

    GridViewColumns are dynamically created and i use MVVM, so it is done actually in a converter like below.

     GridView gv = new GridView();
                    gv.ColumnHeaderContainerStyle= (Style)Application.Current.Resources["GridViewColumnHeaderBackGround_BRUI"];
                    int indexToUse = 0;
                    foreach (var item in config)
                        //bind visible items only
                        //To bind new visible items, the collections requires rebind 
                        if (item.IsVisible)
                            CustomGridViewColumn gridViewCol = new CustomGridViewColumn();
                            item.RunningIdx = indexToUse;
                            gridViewCol.Header = item;      
                            gridViewCol.HeaderTemplate = (DataTemplate)Application.Current.Resources["GridViewColumnHeaderTemplate_BRUI"];
                            gridViewCol.CellTemplate = (DataTemplate)Application.Current.Resources["GridViewCellTemplate_BRUI"];                        
                    return gv;

    GridView is returned with as many columns from the ObservableCollection<List>

    Every List is a row,
    and customstruct instance is column.

    now the problem is in datatemplate, i dont know how to set the index of the List so that i can bind particualr customstruct to the column.

    Earlier i had it as List so using displaymemeberbinding i was bidning it as[{0}]
    in the converter given above.
    now with a customstruct, i need something like [{0}].propertyname but this kind requires celltempalte. and in celltemplate i cannot pass the index.

    I have tried to use your solution. could you please guide. Hopefully code and explaination is meaningfull.

    • Thomas Levesque says:

      I can’t see your template, the markup was stripped by WordPress. Please post it on Gist.

    • Thomas Levesque says:

      I don’t understand exactly what your problem is, but it doesn’t seem related to my blog post… I don’t see any mention of BindingProxy in your code

  68. Jhony says:

    Thanks for the prompt reply. The BindingProxy is used in the datatemplate. I have posted it in gist as “Datatemplate to use binding proxy”.

  69. Ori says:

    Thanks for the brilliant solution.
    I have a DataGrid that one of the columns contains a CheckBox. Your solution solved me the problem of binding the “IsChecked” property of the CheckBox to a property “IsActive” that I have in the ViewModel.
    The problem now is that when I check (or uncheck) a CheckBox in one of the rows – all the CheckBoxes in the column in other rows also get checked. I think (not sure) that the reason for that is that all the rows in the DataGrid get the same instance of the “BindingProxy” object. Maybe I’m wrong but one thing is for sure – this behavior of the DataGrid started after implementing your solution.

    • Thomas Levesque says:

      If you’re binding the checkbox in all the rows to the the same property of the same object, this behavior is perfectly normal.

      IsActive should be a property of the items displayed in the datagrid, not a property of the parent ViewModel. You don’t need BindingProxy at all in that case.

  70. Ten-Seng Guh says:

    Thanks for this great tip. Just wondering if there is a rule on whether a particular control will be part of the visual/logical tree of the main control containing the data context? For example, I noticed that Setter Properties of a style do not appear to be a part of that tree, so I had to use this trick. But is there a rule clearly defined as to when and why?

    • Thomas Levesque says:


      Well, all *controls* are part of the visual tree. Now, something like a DataGridColumn isn’t a control; it’s not even something that’s going to be displayed, it’s just the definition of the column. The DataGrid could add them to its logical children, and that would solve the problem, but it doesn’t. Unfortunately there is no way of knowing that beforehand. So no, there’s no rule.

  71. Raj says:

    Thank you so much, It’s Working

  72. Eric Ouellet says:

    Thanks a lot Thomas.
    Your solution (Freezable for binding) is also extremely valuable for resources. My binding did not happen for an object that inherits from DependencyObject but does when it inherits from Freezable. My object is defined as a Window resource. Since the publication of your article, have you found the rule that makes “Binding” to be created or not created?

  73. suma says:

    it did not work for me. What should be “Data” here.
    Data.MyTitle is not binding data. NEed to initialize BindingProxy and then do Data = ItemSource ?

    • suma says:
              public class GridItem 
                  private string _test;
                  public string Test
                      get ..
      public class GridSample : INotifyCollectionChanged, IEnumerable
          public List _lstItems = new List();
      (MyGrid.ItemsSource as GridSample).Add(
                new GridItem { Test ="Fill Header!"});
      • Thomas Levesque says:

        Hi suma,

        You need to bind BindingProxy.Data to your DataContext, and replace {Binding X} with {Binding Data.X, ElementName=theProxy}

  74. Ron Mittelman says:

    I can’t get this to work. Followed your example pretty closely, except put the XAML part inside the DataGrid.ItemContainerStyle section, because I’m trying to make the entire row visible or collapsed, depending on a field in the row having a certain value. I’m using MultiDataTrigger with 2 conditions: VM property being false and row item’s type column having a particular string value. These 2 conditions being satisfied, the setter simply sets the visibility to collapsed.

    Not sure this works inside the ItemContainerStyle section. Also, your answer on 14 September caused me to wonder: Your example says Data=”{Binding}” in the resources section, but your last answer says to bind BindingProxy.Data to your data context. I’m new enough at WPF to not know about this. Does DataContext=”{Binding}” automatically do this under-the-hood, or do I need to explicitly bind it to the data context? If the latter, how would I do this?

    Thanks, this was a very interesting article.

    • Thomas Levesque says:

      I don’t think you need the BindingProxy at all in this case. Inside the ItemContainerStyle, the DataContext is the value of the current row. Why do you think you need the BindingProxy?

      > Your example says Data=”{Binding}” in the resources section, but your last answer says to bind BindingProxy.Data to your data.

      It’s the same. Data=”{Binding}” binds directly to the DataContext.

      • Ron Mittelman says:

        I think I didn’t properly state my issue. I need the binding proxy because the current row contains a value (EquipmentType) which is a string. The ViewModel contains a boolean(IncludePlatforms), tied to a Checkbox in the View. If I un-check the checkbox, making IncludePlatforms false, I want any items in the DataGrid with EquipmentType of “Platform” to disappear. I’m using a multi-data trigger to test the VM property AND the current row property, and set the current row visibility property accordingly. I’m assuming that ItemContainerStyle, like TextColumn as mentioned in your article, has no connection to the visible tree. If this is true, I need BindingProxy. Please advise. In case you agree, here are my conditions for the MultiDataTrigger (pretend the “[]”‘s are angle brackets):

        [Condition Binding=”{Binding DataContext.EquipmentCategory, RelativeSource={RelativeSource Self}}” Value=”Platform”/]

        [Condition Binding=”{Binding Data.FilterPlatforms, Source={StaticResource proxy}” Value=”false”/]

        If both conditions are true, the Setter sets the Visibility property to false.

        The first condition probably doesn’t need the DataContext and RelativeSource since it refers to the current row’s data, but either way it doesn’t work.

        Can you see from this anything I’m doing wrong?

        • Ron Mittelman says:

          Never mind, for some reason it works now. Don’t know exactly what I changed, but all is ok.
          Thanks so much for your article.

          • Thomas Levesque says:

            Hi Ron,

            Rather than hiding the row from the ItemContainerStyle, you could filter the list at the ViewModel level, by using ICollectionView.Filter:

            var view = CollectionViewSource.GetDefaultView(theCollection);
            view.Filter = somePredicateToFilterItems;
          • Ron Mittelman says:

            Thanks for the filtering idea, Thomas. I will have to evaluate whether we can use that. The problem is, our DataGrid is bound to an editable list object, which we may be in the process of editing different rows on. I’m not sure whether our list object implements ICollectionView. We’re bound to CSLA objects. It’s unclear whether if we edit rows, then apply the filter, then save the object, whether the entire list will be saved or only the unfiltered items.

          • Thomas Levesque says:

            Hi Ron,

            Your collection doesn’t have to implement ICollectionView; when you bind to a collection, WPF implicitly creates a default ICollectionView wrapper for the collection. You can access this wrapper with CollectionViewSource.GetDefaultView(), and apply any filtering, sorting or grouping you need.

            I don’t know about CSLA.NET though, you’ll have to try to be sure

  75. Jay says:

    Thanks! This post was really useful. You saved my day!

4 Trackbacks

Leave a comment