Setting DataContext on a templated control

Topics: Actions & Coroutines
May 10, 2012 at 7:22 AM

I have an ItemsControl which renders its items using a DataTemplate. In its turn, the DataTemplate is styled to use a ControlTemplate. In this ControlTemplate is a Button which when clicked, should remove the item from the ItemsControl.

Here's my XAML:

<ControlTemplate x:Key="DeleteDecoratorTemplate" TargetType="{x:Type Control}">
		<Button cal:Message.Attach="DeleteMyObject($dataContext)" />

<Style x:Key="MyObjectStyle" TargetType="ContentControl">
	<Setter Property="Template">
			<ControlTemplate TargetType="ContentControl">
				<Control x:Name="DeleteDecorator" Template="{StaticResource DeleteDecoratorTemplate}" />

<DataTemplate DataType="{x:Type local:MyObject}">
	<ContentControl Style="{StaticResource MyObjectStyle}">
		<TextBlock Text="{Binding MyValue} "/>

and the current view model:

public void DeleteMyObject(Control control)
	var myObject = control.DataContext as MyObject;
	if (myObject != null)

public void DeleteMyObject(MyObject myObject)

This works OK, but I don't like having the Control overload - I'm guessing that I need to set the button's data context to that of the data template, but I can't figure out the correct binding expression to do that. Is this possible?