UWP 数据绑定:如何将按钮命令设置为 DataTemplate 内的父 DataContext [英] UWP Databinding: How to set button command to parent DataContext inside DataTemplate

查看:23
本文介绍了UWP 数据绑定:如何将按钮命令设置为 DataTemplate 内的父 DataContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需求的简短说明:我需要使用 ViewModel 的 DataContext 中的方法来触发 DataTemplate 内的按钮命令.

Short explanation of need: I need to fire the command of a button inside a DataTemplate, using a method from the DataContext of the ViewModel.

问题的简短说明:模板化按钮命令似乎只能绑定到项目本身的数据上下文.WPF 和 Windows 8.1 应用程序用于向上遍历可视化树的语法似乎不起作用,包括 ElementName 和 Ancestor 绑定.我非常不希望我的按钮命令位于模型内.

Short explanation of problem: The templated button command only seems to be bindable to the datacontext of the item itself. The syntax used by WPF and Windows 8.1 apps to walk up the visual tree doesn't seem to work, including ElementName and Ancestor binding. I would very much prefer not to have my button command located inside the MODEL.

旁注:这是使用 MVVM 设计方法构建的.

Side Note: This is built with the MVVM design method.

以下代码生成 VIEW 上的项目列表.该列表是每个列表项的一个按钮.

The below code generates the list of items on the VIEW. That list is one button for each list item.

            <ItemsControl x:Name="listView" Tag="listOfStories" Grid.Row="0" Grid.Column="1"
            ItemsSource="{x:Bind ViewModel.ListOfStories}"
            ItemTemplate="{StaticResource storyTemplate}"
            Background="Transparent"
            IsRightTapEnabled="False"
            IsHoldingEnabled="False"
            IsDoubleTapEnabled="False"
                 />

在同一个 VIEW 的页面资源中,我创建了一个 DataTemplate,其中包含有问题的按钮.我继续删除按钮内的大部分格式,例如文本,以使代码更易于阅读.除了列出的问题,即命令的绑定之外,与按钮相关的一切都有效.

Inside the page resources of the same VIEW, I have created a DataTemplate, containing the problematic button in question. I went ahead and stripped out most of the formatting inside the button, such as text, to make the code easier to read on this side. Everything concerning the button works, except for the problem listed, which is the binding of the command.

<Page.Resources>
        <DataTemplate x:Name="storyTemplate" x:DataType="m:Story">
            <Button
                Margin="0,6,0,0"
                Width="{Binding ColumnDefinitions[1].ActualWidth, ElementName=storyGrid, Mode=OneWay}"
                HorizontalContentAlignment="Stretch"
                CommandParameter="{Binding DataContext, ElementName=Page}"
                Command="{Binding Source={StaticResource Locator}}">

                <StackPanel HorizontalAlignment="Stretch" >
                    <TextBlock Text="{x:Bind StoryTitle, Mode=OneWay}"
                        FontSize="30"
                        TextTrimming="WordEllipsis"
                        TextAlignment="Left"/>
                </StackPanel>
            </Button>
        </DataTemplate>
    </Page.Resources>

因为这是一个 DataTemplate,DataContext 已设置为组成列表 (MODEL) 的各个项目.我需要做的是选择列表本身的 DataContext (VIEWMODEL),这样我就可以访问导航命令了.

Because this is a DataTemplate, the DataContext has been set to the individual items that comprise the list (MODEL). What I need to do is select the DataContext of the list itself (VIEWMODEL), so I can then access a navigation command.

如果您对 VIEW 页面的代码隐藏感兴趣,请参阅下文.

If you are interested in the code-behind of the VIEW page, please see below.

    public sealed partial class ChooseStoryToPlay_View : Page
    {
    public ChooseStoryToPlay_View()
    {
        this.InitializeComponent();
        this.DataContextChanged += (s, e) => { ViewModel = DataContext as ChooseStoryToPlay_ViewModel; };
    }
    public ChooseStoryToPlay_ViewModel ViewModel { get; set; }
}

我曾尝试通过 ElementName 设置它,还有许多其他尝试,但都失败了.Intellisense 在输入 ElementName 时检测到storyTemplate"作为一个选项,这是本题第一个代码块中显示的 DataTemplate 的名称.

I've tried setting it by ElementName, among many other attempts, but all have failed. Intellisense detects "storyTemplate" as an option when ElementName is input, which is the name of the DataTemplate shown in the first code block of this question.

我不相信我的问题是独一无二的,但是我很难找到 UWP 的解决方案.请允许我提前道歉,这是一个简单的问题,但我花了将近两天的时间研究答案,但似乎没有一个适用于 UWP.

I don't believe my problem can be unique, however I'm having great difficulty finding a solution for UWP. Allow me to apologize in advance in this is a simple question, but I've spent nearly two days researching answers, with none seeming to work for UWP.

谢谢你们!

推荐答案

您正在使用什么 MVVM 工具包(如果有)?在 MVVM Light 中,您可以通过与为视图设置 DataContext 相同的方式从 DataTemplate 获取 ViewModel:

What MVVM toolkit are you using (if any)? In MVVM Light, you can get a hold of ViewModel from DataTemplate same way you set DataContext for your view:

<DataTemplate x:Key="SomeTemplate">
    <Button Command="{Binding Main.MyCommand, Source={StaticResource ViewModelLocator}}"/>
</DataTemplate>

这篇关于UWP 数据绑定:如何将按钮命令设置为 DataTemplate 内的父 DataContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆