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

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.

206 thoughts on “[WPF] How to bind to data when the DataContext is not inherited”

    1. I have been stuck trying to get a multibinding to work for 3 days until I stumbled across this solution. Thank you so very much!

  1. 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?

      1. I am using this way. But its evaluated only once. Value isn’t getting updated

        IsEnabled=”{Binding Data.IsPasteEnabled,Source={StaticResource testProxy},Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, NotifyOnSourceUpdated=True}”

  2. 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!


    1. 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!

  3. 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!


  4. 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?

      1. 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); }
  5. 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.

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

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

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

  7. 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 !!

    1. 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…

  8. 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….?

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

  9. 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….

    1. 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.

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

  11. 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!

  12. 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.

  13. 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.


    1. 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)

      1. Thomas,

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

  14. 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.

  15. 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.

    1. 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.

  16. 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.


  17. 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.


      1. 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!

    1. 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

      1. 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.

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

  18. 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?



  19. Hi,Thomas,

    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.

  20. 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.

    1. 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?

  21. 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?

    1. No, that doesn’t help at all … you need a path to the DataContext, but you don’t have it. The trick here works because the Freezable does have it and you can access the Freezable’s properties.

  22. 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?

    1. 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.

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

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

  23. 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?

    1. 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…

      1. 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.

    1. 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.

  24. 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..

        1. Don’t post it in the comments, the XAML is removed because WordPress treats it as HTML tags… Put it on Gist and post the link here.

          1. Is IsEditVisible a property of the item, or a property of the parent’s DataContext? Does it raise the PropertyChanged event when it changes?

          2. Its Property of item no its not but the collection which I am binding to datagrid raise PropertyChanged event

          3. I’m not sure I understand…

            If it’s a property of an item, it doesn’t make sense to bind the visibility of the column to it: the column can’t be visible for some items and hidden for others…

          4. I have “edit” and “delete” button in my datagrid..sometime on edit button click I just want to hide edit and delete buttons and show update and cancel instead..I tried with CellTemplate and CellEditingTemplate but its not helping..

  25. 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

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

  26. 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 ?

    1. 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.

  27. 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.

  28. 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!

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

  30. 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)

  31. Hi,

    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?


    1. Hi,

      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.

      1. Thanks!
        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.

        1. 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.

  32. 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?

  33. Hi,
    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.

    1. 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

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

  35. 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.

    1. 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.

  36. 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?

    1. Hi,

      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.

  37. 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?

  38. 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 ?

    1.         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!"});
      1. Hi suma,

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

  39. 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.

    1. 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.

      1. 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?

        1. 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.

          1. 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;
          2. 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.

          3. 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

  40. Normally if i bind the TextColumn, it is worked without the above bindingproxy trick and if is use Combobox Column, it won’t work but if i use the above trick, it is worked perfectly, can you share any idea on this,

    Elavarasan M

    1. Hi Elavarasan,

      Binding the Binding property works without the BindingProxy, but it binds to the current item, not to the parent DataContext. If you try to bind any of the column’s other properties, it doesn’t work because the column definition doesn’t inherit a DataContext.

      1. Hi Thomas,

        If I set the datacontext to the window in xaml, it works fine without using the bindingproxy trick, but if I set the datacontext to the window in code behind after InitializeComponent(), it wont work without the bindingproxy trick. Please share any idea on this.

        Thanks in advance.

        Elavarasan M

        1. Without seeing your code, I have no idea. I’m not even sure I understand what you’re saying correctly.

  41. what your mentioned above doesnt seem to be working for me. Your help will be greatly appreciated. here’s the xaml code..

  42. I am trying to do what you mentioned, it doesn’t seem to work. Please help me with this. I have pasted the xaml code below..

    1. Hi San,

      Please post your XAML somewhere else (e.g. Gist or Pastebin), as WordPress strips anything that looks like HTML tags from the comments.

  43. Hi Thomas,

    I like your solution but it is not working totally in my case. Actually, the proxy works as expected but the catch is that I have made a custom type (ContributorCommunication) derived from FrameworkElement and in a TextBlock.Style I attempt to set the TextBlock.Tag property to a current instance of ContributorCommunication. Works the first time but not subsequent times.

    Within a I have

    In this case the proxy behaves as expected with the correct DataContext; however, TextBlock.Tag doesn’t get updated after the first time. I have also tried putting local:ContributorCommunication in and setting the tag via


    and still no luck.

    What am I missing?

    Thank you

    1. Hi Tony,

      Sorry for the delay in answering, I missed the notification somehow…

      I can’t see your code at all, WordPress must have stripped the markup. Could you post it to Gist instead?

  44. Hello Thomas,

    I passed whole Viewmodel as Datacontext in TabItem, so I think all of it’s child element will inherite same Datacontext

    here is my code…

    I have passed a user Controll with Name “RoomGroupControll in Listview” like

    now I want to bind Command from Viewmodel on Button in RoomGroupControl here is code…


    but finally it dosen’t exicutes command on buttonclick

    Can you please help me?

    1. Hi Vijay,

      I don’t see your code, the XAML markup was stripped out by WordPress…

      Could you post it to Gist instead?

        1. You never set the Data property on the proxy, so it’s always null… The proxy isn’t intended to be global for the whole app, it should be local to a view.

  45. Hi,Thomas

    I have this type of scenario in my XAML view

    RoomGroupListView>> (RoomGroupList)



    I can bind cmdExpand to Button but can’t bind RoomList as it’s ItemSource to RoomListView

    Please refer this link to see XAML code

    I have Converted Important Text To UpperCase so it will be easy for you.

    Please help me if you have any idea

    1. So you have a button in a UserControl, and you want to bind it to a command that is in a “parent” ViewModel? You really shouldn’t do that. It makes the UserControl dependent on the context in which it is used. Instead you should bind to a command on the item’s ViewModel.

      1. Hi Thomas,Thanks for you answer, but I don’t get exactly what you want to say. Yes I want to bind Command from Viewmodel on Button,Actuall I can access
        Data.cmdExpand on Button at LowerControl only.

        I want to bind RoomListView also which is in UpperControll but I can’t Do that, like

        but it shows error “Object Referance not set to an instance of object”.

        I don’t get you at this sentence “Instead you should bind to a command on the item’s ViewModel.” can you please explain me in brif?

  46. Hello,

    I spent more than 2 days to find a solution. Thank you, it meant a lot 🙂

    With best regards,

  47. I’m having a tabcontrol in which are 3 views. The solution you provided works, except that it doesn’t refresh the current tab. Meaning, that I have to switch to another tab and back to have the column change visibility. Do you have a suggestion to solve this.

    1. Hi Michel,

      Sorry, I don’t have enough details to suggest a solution… You should post a question on StackOverflow, with all the relevant code.

  48. Fantastic tip!! I had a problem with a ContextMenu not seeing its parent DataContext. No amount of RelativeSource manipulation would fix the problem. I spent about 6 hours looking for a solution to this problem and finally got it working with your fix.

  49. Man, you just saved my job.
    My code freeze was in an hour and I had to finish this issue (I was stuck with this for 3 weeks).
    It worked like a charm.

    Thank You Soooooooooo Much

    1. @Dan sorry for the delay, I didn’t receive the notification…
      My post doesn’t have anything specific to Infragistics, their grid control just happens to be subject to the same issue 😉

  50. Thomas,

    This solution was exactly what I needed for my situation. I was using Infragistics and FieldLayouts, and had the same situation come up.
    Thanks again!

  51. It’s mentioned above, but if not working…..Add “ElementName=Object Name Trying to Bind To”.


    //TO THIS
    //Say MainWindow has x:Name=root):

  52. Thank you November 2017 and this answer is still GOLDEN,
    I actually needed it in a MenuItem and needed it to reference the parent window DataContext and this worked great..
    so added the declaration in the

  53. Thank You for this clever solution. You saved my day. it works fine with IsReadOnly property. Chheers

  54. Thank you very much Thomas. Your solution worked very well for me.
    I actually use it to dynamically translate the header of a DataGridTextColumn using an attached property:


  55. For later versions of Infragistics (v14+ ???, not sure when they added this but it works for me) you can instead use FieldBinding. Here’s an example:

    So the FieldBinding is clearly an Infragistics thing. Would it work with non-Infragistics controls? Not sure, that’s from a XamDataGrid, not sure if it would work with pure WPF, like a ContextMenu or soemthing. Still, for those using Infragistics you might want to try that as well.

    Btw, the BindingProxy does work well and I do like that approach and is a good general solution to this problem.

    1. Well, it stripped out my XAML. Doh!

      Label=”Some Thing”
      Visibility=”{igDP:FieldBinding IsSummerMvaVisible, Converter={x:Static converters:BoolToVisibilityConverter.FalseToCollapsed}}”

      Ok, so you’ll have to imagine the open and close braces there for the XAML. I hope this passes the filter.

  56. Hi, many thanks for this solution. I am able to use this solution in the DataGrid in the project, but I couldn’t make it work for the DataGrid placed as follows. I am using such DataGrid to show the nested list data for each row.

    Any help will be highly appreciated.

  57. Hi, many thanks for this solution. I am able to use this solution in the DataGrid in the project, but I couldn’t make it work for the DataGrid placed inside `DataGrid.RowDetailsTemplate` tag . I am using such DataGrid to show the nested list data for each row.

    Any help will be highly appreciated.
    Please ignore previous comment it removed the content with tags

    1. Hi Ajendra, I still can’t see your code. WordPress strips the XAML markup because it thinks it’s HTML. Please post a link to a Gist instead

  58. I don’t know much about Freezables (even after reading). Why does the class need to inherit from Freezable?

    1. Hi Michael
      As mentioned in the article, I don’t really know how it works. All I know is that this solution doesn’t work if the BindingProxy isn’t a Freezable.

  59. Thanks for the quick response, unfortunately this didnt work for my scenario, can you please suggest how can i bind the property in xaml to change the background color of a control.

    public Brush BackgdColor { get; set; } = new SolidColorBrush(Color.FromArgb(255, 255, 215, 0)); //Property defined in ViewModel

    Binding this property in xaml like,
    BackGround = {Binding BackgdColor}

    but i am getting an error, InvalidOperationException: This Freezable cannot be frozen.

Leave a Reply

Your email address will not be published. Required fields are marked *