I have a list of object that is the data source. Something like that:
public class DataList
{
public List<DataItem> SomeItems;
public void RemoveItem(DataItem item)
{
SomeItems.Remove(item);
}
}
Very simple.
Now I have a XAML that is referenced to this data source. Something like that:
<layout:Accordion ItemsSource="{Binding SomeItems}" SelectionMode="ZeroOrMore" HorizontalAlignment="Stretch"
ItemTemplate="{StaticResource SomeItemTemplate}">
...
where SomeItemTemplate template is defined in App.xaml
<DataTemplate x:Key="SomeItemTemplate">
<Grid>
..
<Button Command={?} Content="Remove" CommandParameter="{Binding}">
</DataTemplate>
How could I bind the command to refer the DataList.RemoveItem? The idea is to pass the item to the parent class (DataList) that knows everything. I can define this method (remove) in the DataItem class itself but in this case I need to pass (in the constructor) the parent class because an item knows nothing about the parent.
Solution is found. See here (http://msdn.microsoft.com/en-us/library/system.windows.data.relativesource%28v=vs.95%29.aspx)
Use
<Button x:Name="btnDeleteItem" Command="{Binding DataContext.RemoveItemCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"
If you’re using silverlight 5, you could use RelativeSource binding:
The idea is to find your higher in hierarchy visual element and take it’s dataContext (DataList).