如何将页面的DataContext中的命令绑定到列表项

3

我有一个页面,其中一个视图模型被设置为它的数据上下文。在该页面上,我有一个列表,它通过视图模型中的一个属性进行填充。列表中包含一个用户控件和一个按钮。我希望将该按钮与视图模型中的一个命令绑定起来。有没有什么方法可以做到这一点?

<Page DataContext=PageViewModel>
...
<ScrollViewer Grid.Row="3" Margin="20,0" Visibility="{Binding ByVenueSelected, Converter={StaticResource BooleanToVisibilityConverter}}">
                <StackPanel>
                    <ItemsControl ItemsSource="{Binding EventsListByVenue}">
                        <ItemsControl.ItemTemplate>
                            <DataTemplate>
                                <myControls:EventDetails /> <!--in this control i want to bind a command available in PageViewModel-->
                            </DataTemplate>
                        </ItemsControl.ItemTemplate>
                    </ItemsControl>
                </StackPanel>
            </ScrollViewer>
...
</Page>

如果你正在使用MVVMlight和静态资源定位器,那么请尝试DataContext = "{Binding MainPageViewModel,Source = {StaticResource Locator}}",否则我需要在稍后使用具有wp dev设置的计算机上查找这个问题。请撤回我的答案。 - FunksMaName
@FunksMaName,我使用这种方式可以工作,除了命令参数为空。 <Button Style="{StaticResource NoHighlightButtonStyle}" Visibility="{Binding link,Converter={StaticResource DataAvailabilityToVisibilityConverter}}" CommandParameter="{Binding Link}" Command="{Binding Path=Event.LinkCommand,Source={StaticResource Locator}}" > <TextBlock Margin="0,5" Foreground="SkyBlue" Text="{Binding link}" TextWrapping="Wrap" FontSize="16"/> </Button> - Ankit
你想要在运行时创建一个动态按钮吗? - Mani
@max 目前还不是,但它属于列表/项控件中的一种,在运行时将被填充。 - Ankit
1个回答

0
在@FunksMaName的帮助下,我解决了这个问题。我相信有更优雅和更好的方法,但是对我来说,这是一个快速且简单的解决方案:
<Button Style="{StaticResource NoHighlightButtonStyle}" Tag="{Binding link}" CommandParameter="{Binding Path=Tag,RelativeSource={RelativeSource Mode=Self}}" Visibility="{Binding link,Converter={StaticResource DataAvailabilityToVisibilityConverter}}" Command="{Binding Path=Event.LinkCommand,Source={StaticResource Locator}}" >
                <TextBlock Margin="0,5" Foreground="SkyBlue" Text="{Binding link}" TextWrapping="Wrap" FontSize="16"/>
</Button>

注意事项: 我认为XAML只在命令的上下文中搜索命令参数,所以它给我返回了空参数,而对于按钮内部的TextBlock,相同的绑定却正常工作。所以我通过将值存储在标签中来欺骗它,并从那里使用它。
Tag="{Binding link}" CommandParameter="{Binding Path=Tag,RelativeSource={RelativeSource Mode=Self}}"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接