c# – UWP数据绑定:如何将按钮命令设置为DataTemplate中的父Dat
需要的简短说明:我需要使用ViewModel的DataContext中的方法触发DataTemplate中的按钮命令.
问题的简短说明:模板化按钮命令似乎只能绑定到项目本身的datacontext. WPF和Windows 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" /> 在同一个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> 因为这是一个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; } } 我试过通过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> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |