2016-03-31 24 views
0

我有一个列表框绑定到我的视图模型(用户控制数据上下文)中的可观察集合。我怎样才能将一个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上?

+0

您可以为您的按钮编写自定义行为。这样你就可以将它绑定到你的按钮上。不知道,这种方法何时应该被解雇? –

回答

1

您可以参考的窗口或页面顶级的DataContext像这样:

<Button Content="{StaticResource Whatever}" 
     DataContext="{Binding DataContext, RelativeSource={RelativeSource AncestorType=Page}}" 
     CommandParameter="{Binding}" 
     Command="{Binding SimpleMethod}" /> 
+0

获得'ListBox'的'DataContext'就足够了。另外,你在绑定中忘记了'Path = SimpleCommand'。这应该是imho后接受的答案。小提示:要么删除'CommandParameter'(OP似乎不需要它),要么在**'Command'之前移动它(参见[这里](http://stackoverflow.com/a/336258/1997232)为什么它很重要)。 – Sinatr

+0

@Sinatr,谢谢你的提示。但是我没有在我的命令中使用'Path',我使用了这个代码,并且它工作正常。 – Crowcoder

+0

你是对的,出于一些奇怪的原因(对我之前的评论感到抱歉),我还没有看到你正在重新分配'DataContext'。不要这样做。而是在'Command'中使用'RelativeSource'绑定自己:'Command =“{Binding DataContext.SimpleMethod,RelativeSource = {RelativeSource FindAncestor,AncestorType = ListBox}}''。 – Sinatr

0

我如何设法解决我的问题:

首先,我创建了一个静态的资源我查看模型。然后,它绑定到我的datacontext在XAML

<UserControl.Resources> 
    <ResourceDictionary> 
     <ResourceDictionary.MergedDictionaries> 
      <ResourceDictionary Source="pack://application:,,,/Styles;component/Resources.xaml" /> 
     </ResourceDictionary.MergedDictionaries> 
     <vm:DeviceSelectorViewModel x:Key="myViewModel" x:Name="myVM" /> 
    </ResourceDictionary> 
</UserControl.Resources> 

<UserControl.DataContext> 
    <StaticResourceExtension ResourceKey="myViewModel"/> 
</UserControl.DataContext> 

这让我那么该命令的源更改为(静态资源)视图模型,像这样:

<Button Width="70" Style="{StaticResource DriveButtonStyle}" Command="{Binding SimpleCommand, Source={StaticResource myViewModel}}" > 

感谢您的答复!

相关问题