views:

22

answers:

1

I've got listbox that employs an item template. Within each item in the list, as defined in the template there is a button. When the user clicks the button I change a value in the data source that defines the sort order of the list. Changing the datasource is not a problem as this is working just fine within my application template.

However my next step is to reload the listbox with the new sorted data source. I've tried doing this from the tempalte but it apparently doesn't have access (or I can't figure out how to get access) to the parent elements so I can reset the .ItemSource property with a newly sorted data source.

Seems like this is possible but the solution is eluding me :(

+1  A: 

You could use databinding to bind the Button's Tag to its ListBox ancestor. Example:

<Grid>
    <Grid.Resources>
        <DataTemplate x:Key="myDataTemplate">
            <Button Tag="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListBox}}"
                        Click="Button_Click">MyButton</Button>
        </DataTemplate>
    </Grid.Resources>

    <ListBox ItemTemplate="{StaticResource myDataTemplate}" ItemsSource="..." />
</Grid>

And here's the codebehind:

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        ListBox myListBox = (ListBox)((Button)sender).Tag;
        ...do something with myListBox...
    }

Alternatively, you can manually climb the Visual Tree upwards in your code (no Tag data binding needed):

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        DependencyObject search = (DependencyObject)sender;
        while (!(search is ListBox)) {
            search = VisualTreeHelper.GetParent(search);
        }
        ListBox myListBox = (ListBox)search;
        ...do something with myListBox...
    }
Heinzi