开发者

Relative binding command with silverlight WP7

开发者 https://www.devze.com 2023-03-16 01:07 出处:网络
I have an error when binding my command to a button in an ItemsControl. This开发者_高级运维 is my code :

I have an error when binding my command to a button in an ItemsControl.

This开发者_高级运维 is my code :

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

with :

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

And I get :

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')..

Of course, I should use an absolute binding or a relative one, but I don't know how to do that.

Thanks in advance for any help


Your Button is within an ItemsControl which is bound to youur MyList property, which I am guessing is a List or some IEnumerable type. The DataContext of each Button will be the item within the MyList that it represents.

You are correct that to bind the buttons to your top-level view model you would need some sort of relative source binding, which Silverlight (3) does not support.

I created a relative source binding replacement for Silverlight here:

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

However, for WP7, where performance really matters, I would not use it!

Why not simply create the relationship you need in your view model? i.e. for each item in MyList (let's call them MyListItem), expose a property which points back to the parent view Model. In other Words, have a MyListItem.Parent property which points to MyViewModel.

0

精彩评论

暂无评论...
验证码 换一张
取 消