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}">
	<Grid>
		<Button cal:Message.Attach="DeleteMyObject($dataContext)" />
	</Grid>
</ControlTemplate>

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

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

and the current view model:

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

public void DeleteMyObject(MyObject myObject)
{
	Items.Remove(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?