我在WPF应用程序中使用DataGrid。它确实为选定的行提供了RowDetails。因此我设置了RowDetailsTemplate。在这个DataTemplate中,我想访问我的Window的DataContext。例如,我在RowDetailsTemplate中有一个标签,我想将它的content-property绑定到我的viewModel的属性,该属性位于窗口的DataContext中。我如何实现这一目标。
感谢您的帮助!
答案 0 :(得分:0)
查看基于RelativeSource的绑定的这种用法,例如{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}
。这是一个例子:
的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>
查看型号:
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)
{
}
在模型类中模拟这个:
public ObservableCollection<String> ClickableItems { get; set; }
的问候,