来自DataTemplate的UWP Master Detail引用父上下文

时间:2018-02-07 17:45:06

标签: c# uwp uwp-xaml master-detail

我无法按照以下草图在UWP主/细节场景中实现删除按钮。

master/details screen layout

我正在使用以下XAML生成屏幕,该屏幕由labelListView组成,两者都使用ContentPresenter绑定到我的视图模型。

DataTemplate

但是,<Page.Resources> <DataTemplate x:Key="MasterListViewItemTemplate" x:DataType="vm:ListItemViewModel"> <StackPanel Orientation="Horizontal"> <SymbolIcon Width="48" Height="48" Symbol="Contact" /> <TextBlock Margin="8,0" VerticalAlignment="Center" Text="{x:Bind Name, Mode=OneWay}" Style="{ThemeResource BaseTextBlockStyle}" /> </StackPanel> </DataTemplate> <DataTemplate x:Key="DetailContentTemplate" x:DataType="vm:ListItemViewModel"> <RelativePanel HorizontalAlignment="Left"> <!-- various input controls --> <!-- Unable to reference command in parent context here --> <Button x:Name="MasterRemoveButton" Padding="12,0" Command="{Binding RemoveCommand}">Remove</button> </RelativePanel> </DataTemplate> </Page.Resources> ... <Grid x:Name="RoleMasterDetailGrid"> <Grid.ColumnDefinitions> <ColumnDefinition x:Name="MasterColumn" Width="Auto" /> <ColumnDefinition x:Name="DetailColumn" Width="*" /> </Grid.ColumnDefinitions> <ListView x:Name="MasterListView" Grid.Column="0" IsItemClickEnabled="True" ItemTemplate="{StaticResource MasterListViewItemTemplate}" ItemsSource="{Binding ListItemViewModels}"> <ListView.Header> <Button x:Name="MasterAddNewButton" Padding="12,0" Command="{Binding AddNewCommand}"> <StackPanel Orientation="Horizontal"> <SymbolIcon Width="48" Height="48" Symbol="AddFriend" /> <TextBlock Margin="8,0" VerticalAlignment="Center" Text="Add" Style="{ThemeResource BaseTextBlockStyle}" /> </StackPanel> </Button> </ListView.Header> </ListView> <ContentPresenter x:Name="DetailContentPresenter" Grid.Column="1" BorderThickness="1,0,0,0" Padding="20,16" BorderBrush="{ThemeResource SystemControlForegroundBaseLowBrush}" Content="{x:Bind MasterListView.SelectedItem, Mode=OneWay}" ContentTemplate="{StaticResource DetailContentTemplate}" /> </Grid> 命令存在于页面视图模型上,而不是RemoveCommand,我似乎找不到从ListItemViewModel DataTemplate中引用它的方法。 1}}。

有人可以建议如何在ContentPresenter

中引用父语境

1 个答案:

答案 0 :(得分:3)

所以这可以通过直接引用你知道data context的元素来实现。它使用Binding ElementName并且效果很好,只要您拥有自己的体面naming并且不会在组件中重复使用templates

只需替换代码中的button声明

即可
<Button x:Name="MasterRemoveButton" Padding="12,0" Command="{Binding RemoveCommand}">Remove</button>

使用以下代码

<Button x:Name="MasterRemoveButton" Content="Remove" Padding="12,0" Command="{Binding ElementName=DetailContentPresenter Path=DataContext.RemoveCommand}"/>