将命令绑定到嵌套列表框

时间:2015-12-09 23:16:46

标签: c# wpf mvvm listbox

我试图将一个Command绑定到itemsControl中的嵌套ListBox,但不知怎的,我无法找到正确的DataContext来执行命令。

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);
    }
}

我已经尝试了

 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}}}" />

这两个选项都不起作用。

1 个答案:

答案 0 :(得分:1)

您需要访问DataContext中的根UserControl

UserControl

添加名称
x:Name="MyUserControl"

然后为你的命令:

Command"{Binding ElementName=MyUserControl, Path=DataContext.DeleteSelectedPartialCommand}"
相关问题