Cannot bind command within a ListBox

荒凉一梦 提交于 2021-02-05 10:48:05

问题


My WPF uses the MVVM approach. I'm trying to bind 2 controls within my list control

<ListBox ItemsSource="{Binding ParentDuplicate}" SelectedItem="{Binding SelectedParent, UpdateSourceTrigger=PropertyChanged}">
    <ListBox.ItemTemplate>
         <DataTemplate>
             <StackPanel>
                    <ContentControl Content="{Binding}" />
                    <Button Content="Delete me now" 
                            Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorLevel=1, AncestorType=Window}, Path=DeleteCommand}" 
                            CommandParameter="{Binding FilePath}" />
              </StackPanel>
           </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

The problem I'm having, is the DeleteCommand is not binding (the Ouput window informs me as well)

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Data.Binding', AncestorLevel='1''. BindingExpression:Path=DeleteCommand; DataItem=null; target element is 'Button' (Name=''); target property is 'Command' (type 'ICommand')

If I move this button to outside the ListBox, then the binding works and the event fires so I know the issue must be with the ListBox (I'm guessing the problem is the ItemsSource prevents the binding to anything but the ItemsSource bound property (in this case, ParentDuplicate))

So, within the Button control, there are 2 properties being bound, DeleteCommand and FilePath

Both of these properties live within my single ViewModel. FilePath is a child of ParentDuplicate and this binds as desired. The issue is only with the DeleteCommand. What am I doing wrong?

Edit

When I use the Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorLevel=1, AncestorType=Window}, Path=DeleteCommand} it is looking in my MainWindow code behind, not at the ViewModel. How do I make it use the ViewModel?

I tried

Command="{Binding RelativeSource={RelativeSource  AncestorType=xmlnsViewModel:MainWindowViewModel}, Path=DeleteCommand}" 

but the above also results in the same binding errors


回答1:


The ancestor search finds the control, not the DataContext, so you'll need to tell your binding where to find the DeleteCommand property. If your ViewModel is the DataContext of the MainWindow then you can just use:

<Button Content="Delete me now" 
    Command="{Binding RelativeSource={RelativeSource 
                  Mode=FindAncestor, AncestorLevel=1, AncestorType=Window}, 
                  Path=DataContext.DeleteCommand}" 
    CommandParameter="{Binding FilePath}" />


来源:https://stackoverflow.com/questions/20523347/cannot-bind-command-within-a-listbox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!