[英]Access the Window's DataContext from a DataTemplate in a DataGrid
I use a DataGrid in my WPF application. 我在WPF应用程序中使用了DataGrid。 It does feature RowDetails for selected Rows.
它具有针对选定行的RowDetails。 Therefor I set the RowDetailsTemplate.
为此,我设置了RowDetailsTemplate。 Inside this DataTemplate i want to access my Window's DataContext.
在此DataTemplate内,我想访问Window的DataContext。 For Example I have a lable inside my RowDetailsTemplate and I want to bind it's content-property to a property of my viewModel which is in the DataContext of the window.
例如,我在RowDetailsTemplate内有一个标签,我想将其内容属性绑定到我的viewModel的属性中,该属性位于窗口的DataContext中。 How do I achieve this.
我该如何实现。
Thank you for your help! 谢谢您的帮助!
Look at this usage of RelativeSource based binding, like {Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}
. 查看这种基于RelativeSource的绑定用法,例如
{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}
。 Here is example: 这是示例:
Xaml: Xaml:
<DataGrid ItemsSource="{Binding Strings}" AutoGenerateColumns="False" > <DataGrid.Columns> <DataGridTemplateColumn Header="String" Width="SizeToCells" IsReadOnly="True"> <DataGridTemplateColumn.CellTemplate> <DataTemplate DataType="{x:Type soDataGridHeplAttempt:ClicableItemsModel}"> <ListBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ItemsSource="{Binding ClickableItems}"> <ListBox.ItemsPanel> <ItemsPanelTemplate> <StackPanel Orientation="Horizontal"></StackPanel> </ItemsPanelTemplate> </ListBox.ItemsPanel> <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="ContentTemplate"> <Setter.Value> <DataTemplate> <Button Width="70" Content="{Binding }" Style="{StaticResource ButtonInCellStyle}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=DataContext.Command}" CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Content}"/> </DataTemplate> </Setter.Value> </Setter> </Style> </ListBox.ItemContainerStyle> </ListBox> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid>
View model: 查看模型:
private ICommand _command; public ObservableCollection<ClicableItemsModel> Strings { get; set; } public ICommand Command { get { return _command ?? (_command = new RelayCommand<object>(MethodOnCommmand)); } } private void MethodOnCommmand(object obj) { }
Model pu this inside the the model class: 在模型类内部对此进行建模:
public ObservableCollection<String> ClickableItems { get; set; }
regards, 问候,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.