【问题标题】:how to bind a command from DataContext of Page to a list item如何将Page的DataContext中的命令绑定到列表项
【发布时间】:2013-09-18 09:53:50
【问题描述】:

我有一个页面,并且视图模型被设置为其数据上下文。在那个页面我有一个列表。这是通过视图模型中的属性填充的。 List 有一个用户控件。并且该用户控件有一个按钮。我希望该按钮与视图模型中的命令绑定。有什么办法吗?

<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 以这种方式使用它对我有用,除了命令参数为空。
  • 你想在运行时创建一个按钮吗?动态?
  • @max 没有,但它的某种,在 List/ItemsControl 中,它将在运行时填充

标签: c# xaml windows-phone-7


【解决方案1】:

在@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 仅在命令的上下文中搜索命令参数,因此它给了我空参数,而相同的绑定对于按钮内的文本块工作正常。所以我欺骗它把值存储在标签中,并从那里使用它。

Tag="{Binding link}" CommandParameter="{Binding Path=Tag,RelativeSource={RelativeSource Mode=Self}}"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-02
    • 2022-01-18
    • 1970-01-01
    • 2010-12-05
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    • 2018-11-06
    相关资源
    最近更新 更多