0


I have a datagrid, which is filled by a datatable. Each entry in the table is an object of a custom type. For each cell I want to use an usercontrol to show the content. I use XamlReader to create the usercontrol in code behind. I learned that the DataContext of the DataTemplate for the columns CellTemplate is a DataGridRow and I could access an element with the following code:

$@"<DataTemplate
     xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"">
     <TextBox Text=""{{Binding [{count}].Amount}}"" /> 
   </DataTemplate>"

When I try the same with my usercontrol it fails:

$@"<DataTemplate 
     xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""> 
     <local:MyControl 
        MyProperty=""{{Binding [{count}]}}""  
        xmlns:local=""...

with the error:

BindingExpression path error: '[]' property not found on 'object'

Is the DataContext different when I use custom control? I don't get it...

Sascha
  • 65
  • 7
  • You did not by accident explicitly set the DataContext of MyControl somewhere, e.g. in its constructor? – Clemens Jan 11 '18 at 10:30
  • ehm, of course I did... in the xaml of the control I have `DataContext="{Binding RelativeSource={RelativeSource Self}}"` but I just removed it without success (but the binding doesn't use the DataContext of the control, does it? wouldn't make any sense since I want to pass arguments from the outside...) – Sascha Jan 11 '18 at 10:41
  • 1
    It does. You should therefore never explicitly set a control's DataContext, because it breaks Bindings intended to the inherited DataContext. Also check if you have `DataContext = this;` in the ctor, and remove that. To bind to the control's properties in its own XAML, use `RelativeSource AncestorType=UserControl`. – Clemens Jan 11 '18 at 10:43
  • Like I said I just removed it, but still the same error... and the constructor is clean. The confusing thing is: property not found on 'object', so WHAT is the DataContext? – Sascha Jan 11 '18 at 10:48
  • When you don't set it explictly, the DataContext is obviously the same as in the TextBox example, i.e. the one inherited from the control's parent element. However, "I use XamlReader to create the usercontrol in code behind" sounds dubious. You should perhaps show us how exactly you're doing that, or better, not do it all. Maybe use a DataTemplateSelector instead. – Clemens Jan 11 '18 at 10:52
  • Is there any particular reason why, you're using code behind to generate xaml? – XAMlMAX Jan 11 '18 at 11:20
  • @Clemens Turned out you were right... I have multiple controls which similar names, I removed the DataContext from the wrong one... – Sascha Jan 11 '18 at 11:24
  • You should still consider using a DataTemplateSelector. Take a look at the DataGrid's ItemTemplateSelector property. – Clemens Jan 11 '18 at 11:28

0 Answers0