我有一个列表框绑定到我的视图模型(用户控制数据上下文)中的可观察集合。我怎样才能将一个DataTemplate中的按钮的命令设置为父元素的数据上下文
DeviceDetector driveDetector;
public DriveSelector()
{
InitializeComponent();
driveDetector = DeviceDetector.Instance;
DataContext = driveDetector;
}
这是我为我的列表框
<ListBox Style="{StaticResource ListBoxStyle}" ItemsSource="{Binding DriveCollection}">
<ListBox.ItemTemplate>
<DataTemplate>
<Button Width="70" Style="{StaticResource DriveButtonStyle}" Command="{Binding SimpleMethod}">
<StackPanel>
<Image Source="{Binding Image}" Style="{StaticResource DriveImageStyle}"/>
<Label Content="{Binding Name}" Style="{StaticResource DriveLabelStyle}"/>
</StackPanel>
</Button>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我已经实现ICommand的,当我的列表框之外绑定到的命令,像这样的代码:
<Button Command="{Binding SimpleMethod}"/>
一切都很好。然而,当我尝试将命令绑定到按钮的ListBox的DataTemplate中内我得到这个错误:
System.Windows.Data Error: 40 : BindingExpression path error: 'SimpleMethod' property not found on 'object' ''DriveInfo' (HashCode=6377350)'. BindingExpression:Path=SimpleMethod; DataItem='DriveInfo' (HashCode=6377350); target element is 'Button' (Name=''); target property is 'Command' (type 'ICommand')
我可以看到按钮的datacontext是到模型等方法“SimpleMethod”无法找到。有没有一种方法可以将命令绑定到列表框本身的datacontext上?
您可以为您的按钮编写自定义行为。这样你就可以将它绑定到你的按钮上。不知道,这种方法何时应该被解雇? –