2011-06-28 49 views
0

将我的命令绑定到ItemsControl中的按钮时出现错误。Silverlight的相对绑定命令WP7

这是我的代码:

<phone:PhoneApplicationPage.DataContext> 
    <ViewModel:MyViewModel /> 
</phone:PhoneApplicationPage.DataContext> 

有:

<ItemsControl ItemsSource="{Binding MyList}"> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate> 
      <Button Content="Test" 
       cmd:ButtonBaseExtensions.Command="{Binding MyViewModel.TestCommand}" 
       cmd:ButtonBaseExtensions.CommandParameter="{Binding}"/> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 

我也得到:

System.Windows.Data Error: BindingExpression path error: 'MyViewModel' property not found on '...' '...' (HashCode=77119633). BindingExpression: Path='MyViewModel.ChooseCommand' DataItem='...' (HashCode=77119633); target element is 'System.Windows.Controls.Button' (Name=''); target property is 'Command' (type 'System.Windows.Input.ICommand').. 

当然,我应该用一个绝对的约束力还是一个相对,但我不知道该怎么做。

预先感谢任何帮助

回答

1

Button是必然youur MyList属性,我猜是一个列表或者一些IEnumerable类型的ItemsControl内。每个ButtonDataContext将是它所代表的MyList内的项目。

如果要将按钮绑定到顶层视图模型,则需要某种相对源绑定,Silverlight(3)不支持这种绑定。

我创建了一个相对的发射源的Silverlight这里结合置换:

http://www.scottlogic.co.uk/blog/colin/2009/02/relativesource-binding-in-silverlight/

然而,对于WP7,其中性能真的很重要,我不会用它!

为什么不简单地在你的视图模型中创建你需要的关系?即对于MyList(我们称之为MyListItem)中的每个项目,公开一个指向父视图模型的属性。换句话说,有一个MyListItem.Parent属性指向MyViewModel

+0

好主意,它有点不舒服^^但它的工作,谢谢 – Tim