1

I am binding to an ObservableCollection<Stage> Stages as the ItemsSource for an ItemsControl:

<ItemsControl ItemsSource="{Binding Path=Stages}">

Is there any way to pass the current stage object to a usercontrol in an item datatemplate like this:

<ItemsControl ItemsSource="{Binding Path=Stages}">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type local:Stage}">
    <local:MyUserControl CustomDependencyProperty="{Binding}" />
</DataTemplate>
</ItemsControl.ItemTemplate>

The real problem is I need to have the current Stage object to be a variable in MyUserControl to do some work on it. Passing it to the constructor [like: MyUserControl(Stage s)] seems like a good way of doing it but afaik there is no way to specify that in XAML. Any ideas?

user374735
  • 11
  • 2
  • If I understood you correctly by the current Stage object you mean object corresponding to the item within ItemsControl. It is the function of ItemsControl to map each element of its ItemsSource to DataContext of generated item in Items list. Since plain {Binding} binds directly to DataContext, you did exactly the right thing in your code - bound MyUserControl.CustomDependencyProperty to corresponding element in your ObservableCollection. – repka Jun 24 '10 at 00:46
  • Also, passing it via constructor is not recommended: if ItemControls uses virtual panels it'll reuse items created previously if they disappear from screen by changing their DataContext to whatever showed up instead. – repka Jun 24 '10 at 00:48
  • I'm getting the following errors in the VS Output window at run time when I try to do the above: Cannot create default converter to perform 'one-way' conversions between types 'StageControl' and 'Stage'. Consider using Converter property of Binding. BindingExpression:Path=; DataItem='StageControl', target element is 'StageControl'target property is 'Stage' Value produced by BindingExpression is not valid for target property.; Value='StageControl' BindingExpression:Path=; DataItem='StageControl' (Name=''); target element is 'StageControl' (Name=''); target property is 'Stage' – user374735 Jun 25 '10 at 20:22
  • To be a little more clear and to align with my post above, when I set CustomDependencyProperty as shown above, I get the conversion error above. The {Binding} should be returning a Stage object, and CustomDependencyProperty accepts Stage objects... so I don't see what the problem is. Again, the exact errors are in my previous comment, where StageControl is MyUserControl, and Stage is my CustomDependencyProperty which accepts objects of type Stage. Any idea? Thanks for the help! – user374735 Jun 25 '10 at 20:43

0 Answers0