c# – UWP数据绑定:如何将按钮命令设置为DataTemplate中的父DataContext

前端之家收集整理的这篇文章主要介绍了c# – UWP数据绑定:如何将按钮命令设置为DataTemplate中的父DataContext前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
需要的简短说明:我需要使用viewmodel的DataContext中的方法触发DataTemplate中的按钮命令.

问题的简短说明:模板化按钮命令似乎只能绑定到项目本身的datacontext. WPFWindows 8.1应用程序用于浏览可视化树的语法似乎不起作用,包括ElementName和Ancestor绑定.我非常不希望我的按钮命令位于MODEL内部.

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

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

<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"
                 />@H_404_9@ 
 

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

<Page.Resources>
        <DataTemplate x:Name="storyTemplate" x:DataType="m:Story">
            <Button
                Margin="0,6,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>@H_404_9@ 
 

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

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

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; }
}@H_404_9@ 
 

我试过通过ElementName设置它,在许多其他尝试中,但都失败了.当输入ElementName时,Intellisense会将“storyTemplate”检测为选项,这是此问题的第一个代码块中显示的DataTemplate的名称.

我不相信我的问题可能是独特的,但是我很难找到UWP的解决方案.请允许我提前道歉这是一个简单的问题,但我花了将近两天的时间来研究答案,似乎没有人能为UWP工作.

感谢你们!

解决方法

你使用什么MVVM工具包(如果有的话)?在MVVM Light中,您可以从DataTemplate获取viewmodel,就像为视图设置DataContext一样:
<DataTemplate x:Key="SomeTemplate">
    <Button Command="{Binding Main.MyCommand,Source={StaticResource viewmodelLocator}}"/>
</DataTemplate>@H_404_9@
原文链接:https://www.f2er.com/csharp/99914.html

猜你在找的C#相关文章