简体   繁体   中英

Binding to Usercontrol Datacontext instead of SelectedItems datacontext

I have a listbox, where a grid with textboxes shows the listboxs currently selecteditems data. (Code below)

The problem is that i want a delete button inside this grid, however the command it uses lies in the Usercontrols DataContext. How do I make the button recieve the command binding inside the UserControls Datacontext?

Following code lies inside a grid where the visual trees root is a UserControl.

        <ListBox Name="list" ItemTemplate="{StaticResource listTemplate}" ItemsSource="{Binding listCollection, UpdateSourceTrigger=PropertyChanged}">
        </ListBox>

        <Grid DataContext="{Binding ElementName=list, Path=SelectedItem}" Grid.Row="1">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
        </Grid.RowDefinitions>
        <TextBlock Margin="7">Name:</TextBlock>
        <TextBox Margin="5" Grid.Column="1" Text="{Binding Path=Name}"></TextBox>
        <Button Grid.Row="1" Command="{Binding DeleteSelectedItemCommand}">Delete Selected Item</Button>
        </Grid>

You mean you want to fire the button's command on your UserControls DataContext IE your vm? Then you need this binding;

<Button Grid.Row="1" Command="{Binding Path=DeleteSelectedItemCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type YourControl}}}">Delete Selected Item</Button>

Basicly this just traverse up your xaml tree and fetch datacontext from the control called YourControl. You could set UserControl here. The cool thing about this kind of binding is that you may track back the datacontext of any items up the chain :)

This document is still very handy for bindings that are a bit tricky :)

Cheers,

Stian

您需要更改DataContext,为UserControl提供相同的名称,然后

Command="{Binding ElementName=Name, Path=DeleteSelectedItemCommand}"

The trick was to wire up the DataContext using Stians reference.

<Button 
DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType {x:Type UserControl}}, Path=DataContext}" 
Command="{Binding Path=DeleteSelectedItemCommand}">
</Button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM