绑定到Windows Phone 7项目数据模板内的MVVM Light中继命令

Jos*_*arl 4 windows-phone-7 mvvm-light

我正在尝试使用MVVM Light命令将按钮绑定到viewmodel命令,并且由于某种原因,该命令似乎没有被调用.通常我没有使用命令的任何问题,但这个似乎忽略了绑定.

这是我的代码:

<ListBox.ItemTemplate>
    <DataTemplate>
        <StackPanel>
            <Button>
                <Interactivity:Interaction.Triggers>
                    <Interactivity:EventTrigger EventName="Click">
                        <Command:EventToCommand 
                            Command="{Binding MyButtonClickAction}" />
                    </Interactivity:EventTrigger>
                </Interactivity:Interaction.Triggers>
            </Button>

            <StackPanel>
                <TextBlock Text="{Binding MyProperty}"/>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding MyOtherProperty}" />
                </StackPanel>
            </StackPanel>
        </StackPanel>
    </DataTemplate>
</ListBox.ItemTemplate>
Run Code Online (Sandbox Code Playgroud)

此数据模板位于我的应用程序启动后创建的列表中,我想知道这是否是问题所在.我的理论是创建了视图模型,构造函数尝试使用relay命令设置绑定,但由于列表还没有任何项目,绑定以某种方式失败.

MyProperty和MyOtherProperty的绑定工作正常.

有关如何使其工作的任何建议?

Mat*_*ton 7

问题是在DataTemplate中,DataContext是项本身,而不是ViewModel.所以当你说{Binding MyButtonActionClick},绑定正在寻找一个MyButtonActionClick项目上调用的命令,我猜测它只是一个简单的对象,并且没有自己的命令属性.

有几种方法可以解决这个问题.由于您已经在使用MMVM Light,因此最好的方法可能是将您的集合定义为List<FooViewModel>而不是List<Foo>将您的项目包装在自己的ViewModel类中.然后,您可以MyButtonActionClick向该ViewModel 添加一个命令,并将该调用返回到父ViewModel.

否则,更改命令绑定,以便查看ItemsControl本身的DataContext.看看这个问题(以及当然接受的答案),了解如何做到这一点的一些想法.

  • 在MVVM Light中,您还可以通过ViewModelLocator找到VM.我个人更喜欢这个.绑定变为{Binding Source = {StaticResource Locator},Path = Main.MyCommand}其中Main是托管MyCommand的VM (6认同)

Pau*_*ton 7

作为旁注,您可能需要在将命令与按钮关联时考虑使用ButtonBaseExtensions类.可以在GalaSoft.MvvmLight.WP7程序集中的GalaSoft.MvvmLight.Command命名空间中找到此类.

您的命名空间XAML将包括: -

xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.WP7"
Run Code Online (Sandbox Code Playgroud)

你的按钮XAML看起来像这样: -

<Button cmd:ButtonBaseExtensions.Command="{Binding MyButtonClickAction}"/>
Run Code Online (Sandbox Code Playgroud)