0

I'm trying to bind a Command to a nested ListBox inside an itemsControl but somehow I can't find the right DataContext to execute the command.

XAML

<UserControl DataContext="{Binding VM1, Source={StaticResource Locator}}"
  <ItemsControl  ItemsSource="{Binding SceneList}"

    <ListBox ItemsSource="{Binding PartialScenes}" 
             SelectedItem="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}, Path=DataContext.SelectedPartialScene}" >
         <ListBox.InputBindings>
              <KeyBinding Key="Delete" Command="{Binding DeleteSelectedPartialCommand}"/>
         </ListBox.InputBindings>
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel>
                            <TextBlock>
                                  <Run Text="{Binding Path=Label}"/>
                            </TextBlock>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate> 
    </ListBox>
  </ItemsControl
</UserControl

VM

public class VM1
{
    public()
    {
          DeleteSelectedPartialCommand= new RelayCommand(Delete); 
    }

    public RelayCommand DeleteSelectedPartialCommand{ get; private set; }
    private void Delete()
    {
        Collection.Remove(SelectedItem);
    }
}

I've tried

 Command="{Binding Path=DataContext.DeleteSelectedPartialCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}" />

 and

 Command="{Binding Path=DataContext.DeleteSelectedPartialCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}" />

Both options are not working.

1 Answer 1

1

You need to access the root DataContext which is in UserControl.

Add a name to your UserControl

x:Name="MyUserControl"

And then for your command:

Command"{Binding ElementName=MyUserControl, Path=DataContext.DeleteSelectedPartialCommand}"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.