C # / WPF - DataGrid - привязка ширины TextBox в RowDetails к ширине содержащей DataGrid - PullRequest
2 голосов
/ 01 августа 2011

Моя проблема похожа на эту;

За исключением того, что я хотел бы, чтобы детали строк никогда не превышали ширинуиз столбцов, которые он охватывает.

|--0--|--1--|--2--|--3--|--4--|
|---------Row-Details---------|

Я пробовал AreRowDetailsFrozen, и это не имело никакого эффекта.Я также пытался привязать к фактической ширине родительской сетки (OneWay), но это приводит к тому, что ширина превышает ширину двух моих экранов.

Вот моя текущая попытка (упрощенно);

  <Grid>
    <DataGrid x:Name="Grid" 
              Grid.Row="1" 
              ItemsSource="{Binding Collection}"
              IsReadOnly="True"
              AutoGenerateColumns="False" 
              ColumnWidth="Auto"
              CanUserResizeColumns="False"
              CanUserResizeRows="False"
              RowDetailsVisibilityMode="VisibleWhenSelected"
              AreRowDetailsFrozen="True"
              SelectionUnit="FullRow"
              VerticalAlignment="Top"
              HorizontalAlignment="Center">
        <DataGrid.RowDetailsTemplate>
           <!-- Begin row details section. -->
           <DataTemplate>
               <TextBox DataContext="{Binding ErrorMessage}" 
                       IsReadOnly="True"
                       Margin="5"
                       BorderBrush="Transparent"
                       ScrollViewer.VerticalScrollBarVisibility="Auto"
                       ScrollViewer.CanContentScroll="True"
                       TextWrapping="Wrap"
                       Text="{Binding .}">
               </TextBox>
           </DataTemplate>
        </DataGrid.RowDetailsTemplate>
   </DataGrid>
  </Grid>

Это приводит к следующему:

|--0--|--1--|--2--|--3--|--4--|
|---------Row-Details are as wide as the longest row in their content ---------|

Привязка ширины TextBox к любому родительскому контейнеру (Grid, DataGrid, ItemsPresenter):

Width="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Grid}}, Path=ActualWidth, Mode=OneWay}"

Результат:

                              |------Viewable Area-------|
|---- Columns ----|
|---------Row-Details --------------------------------------------------------------|

Это очень расстраивает, я просто хочу, чтобы Детали строк не меняли ширину DataGrid, это так много, чтобы спросить?:)

Ответы [ 3 ]

1 голос
/ 01 августа 2011

Единственный способ сделать это - изменить DataGridRow ControlTemplate.Там мы можем привязать ширину хоста деталей строки (DataGridDetailsPresenter) к ширине ячеек.Например:

<Style x:Key="{x:Type dg:DataGridRow}" TargetType="{x:Type dg:DataGridRow}">
    <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.WindowBrushKey}}" />
    <Setter Property="SnapsToDevicePixels" Value="true"/>
    <Setter Property="Validation.ErrorTemplate" Value="{x:Null}" />
    <Setter Property="ValidationErrorTemplate">
      <Setter.Value>
        <ControlTemplate>
          <TextBlock Margin="2,0,0,0" VerticalAlignment="Center" Foreground="Red" Text="!" />
        </ControlTemplate>
      </Setter.Value>
    </Setter>
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="{x:Type dg:DataGridRow}">
          <Border x:Name="DGR_Border"
                  Background="{TemplateBinding Background}"
                  BorderBrush="{TemplateBinding BorderBrush}"
                  BorderThickness="{TemplateBinding BorderThickness}"
                  SnapsToDevicePixels="True">
            <dgp:SelectiveScrollingGrid>
              <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="*"/>
              </Grid.ColumnDefinitions>

              <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="Auto"/>
              </Grid.RowDefinitions>

              <dgp:DataGridCellsPresenter x:Name="cellPresenter" Grid.Column="1"
                                         ItemsPanel="{TemplateBinding ItemsPanel}"
                                         SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>

              <dgp:DataGridDetailsPresenter  dgp:SelectiveScrollingGrid.SelectiveScrollingOrientation="{Binding RelativeSource={RelativeSource AncestorType={x:Type dg:DataGrid}}, Path=AreRowDetailsFrozen, Converter={x:Static dg:DataGrid.RowDetailsScrollingConverter}, ConverterParameter={x:Static dg:SelectiveScrollingOrientation.Vertical}}"
                                            Grid.Column="1" Grid.Row="1"
                                            Visibility="{TemplateBinding DetailsVisibility}" Width="{Binding ElementName=cellsPresenter, Path=ActualWidth}"/>

              <dgp:DataGridRowHeader dgp:SelectiveScrollingGrid.SelectiveScrollingOrientation="Vertical"  Grid.RowSpan="2"
                                    Visibility="{Binding RelativeSource={RelativeSource AncestorType={x:Type dg:DataGrid}}, Path=HeadersVisibility, Converter={x:Static dg:DataGrid.HeadersVisibilityConverter}, ConverterParameter={x:Static dg:DataGridHeadersVisibility.Row}}"/>
            </dgp:SelectiveScrollingGrid>
          </Border>
        </ControlTemplate>
      </Setter.Value>
    </Setter>
  </Style>

Надеюсь, это поможет.

0 голосов
/ 25 января 2012

Я нашел другой способ решения проблемы:

private void GridOnLoadingRowDetails(object sender, DataGridRowDetailsEventArgs e)
{
    var dataGridColumnHeadersPresenter = FindVisualChild<DataGridColumnHeadersPresenter>((DataGrid)sender);
    e.DetailsElement.SetBinding(WidthProperty, new Binding("ActualWidth") { Source = dataGridColumnHeadersPresenter });
}

Это не позволяет вам использовать постоянные значения (например, '6') - что не подходит, если кто-то установил DataGrid.RowHeaderWidth -и конвертеры.

Я добавил это в обработчик событий DataGrid.LoadingRowDetails, так как уже настраиваю RowDetails другими способами.

0 голосов
/ 21 октября 2011

Я ответил на аналогичный вопрос здесь DataGrid RowDetails Width проблема

Ответы здесь выглядят как обходной путь, поэтому я провел небольшое исследование и сделал найти решение на форумах Telerik, так как мы используем их RadGridView. Оказалось, что решение работает и для DataGrid.

Ключ в том, чтобы установить ScrollViewer.HorizontScrollBarVisibility свойство Disabled, см. пример ниже.

<DataGrid ScrollViewer.HorizontalScrollBarVisibility="Disabled">
<DataGrid.RowDetailsTemplate>
    <DataTemplate>
        <Border>
            <TextBlock Foreground="White" Text="{Binding RowDetails}"
                       TextWrapping="Wrap"/>
        </Border>
    </DataTemplate>
</DataGrid.RowDetailsTemplate> </DataGrid>
...