C# 无法在列表框中绑定命令
我的WPF使用MVVM方法。我正在尝试绑定列表控件中的2个控件C# 无法在列表框中绑定命令,c#,wpf,mvvm,C#,Wpf,Mvvm,我的WPF使用MVVM方法。我正在尝试绑定列表控件中的2个控件 <ListBox ItemsSource="{Binding ParentDuplicate}" SelectedItem="{Binding SelectedParent, UpdateSourceTrigger=PropertyChanged}"> <ListBox.ItemTemplate> <DataTemplate> <Stack
<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>
但是上面的操作也会导致相同的绑定错误祖先搜索会找到控件,而不是DataContext,因此您需要告诉绑定在哪里可以找到DeleteCommand属性。如果ViewModel是主窗口的DataContext,则可以使用:
<Button Content="Delete me now"
Command="{Binding RelativeSource={RelativeSource
Mode=FindAncestor, AncestorLevel=1, AncestorType=Window},
Path=DataContext.DeleteCommand}"
CommandParameter="{Binding FilePath}" />
祖先搜索找到的是控件,而不是DataContext,因此您需要告诉绑定在哪里可以找到DeleteCommand属性。如果ViewModel是主窗口的DataContext,则可以使用:
<Button Content="Delete me now"
Command="{Binding RelativeSource={RelativeSource
Mode=FindAncestor, AncestorLevel=1, AncestorType=Window},
Path=DataContext.DeleteCommand}"
CommandParameter="{Binding FilePath}" />
祖先搜索找到的是控件,而不是DataContext,因此您需要告诉绑定在哪里可以找到DeleteCommand属性。如果ViewModel是主窗口的DataContext,则可以使用:
<Button Content="Delete me now"
Command="{Binding RelativeSource={RelativeSource
Mode=FindAncestor, AncestorLevel=1, AncestorType=Window},
Path=DataContext.DeleteCommand}"
CommandParameter="{Binding FilePath}" />
祖先搜索找到的是控件,而不是DataContext,因此您需要告诉绑定在哪里可以找到DeleteCommand属性。如果ViewModel是主窗口的DataContext,则可以使用:
<Button Content="Delete me now"
Command="{Binding RelativeSource={RelativeSource
Mode=FindAncestor, AncestorLevel=1, AncestorType=Window},
Path=DataContext.DeleteCommand}"
CommandParameter="{Binding FilePath}" />
基本上,RelativeSource搜索可视化树,而您的DataContext/ViewModel不在其中。它是可视元素的一个属性。基本上,RelativeSource搜索可视树,而您的DataContext/ViewModel不在其中。它是可视元素的一个属性。基本上,RelativeSource搜索可视树,而您的DataContext/ViewModel不在其中。它是可视元素的一个属性。基本上,RelativeSource搜索可视树,而您的DataContext/ViewModel不在其中。它是一个可视元素的属性。我最终使用了命令=“{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorLevel=1,AncestorType=Grid},Path=DataContext.DeleteCommand}”谢谢你,我最终使用了命令=“{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorLevel=1,AncestorType=Grid}”,Path=DataContext.DeleteCommand}“谢谢你,我最后使用了Command=“{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorLevel=1,AncestorType=Grid},Path=DataContext.DeleteCommand}”谢谢你,我最后使用了Command=“{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorLevel=1,AncestorType=Grid}”,Path=DataContext.DeleteCommand}“谢谢