Измените цвет фона Заголовка Datagrid в Silverlight

Это проблема с сериализацией. Вы пытаетесь вернуть сложный объект, который не предназначен для прямой сериализации. Вместо этого вам следует перебирать документы в снимке запроса, создавать любой объект, который вы хотите вернуть (массив?), И возвращать его. Примерно так:

const querySnapshot = await db.collection('test').get();
return querySnapshot.docs.map(doc => doc.data());
8
задан David Padbury 22 May 2011 в 17:11
поделиться

2 ответа

Хотя DataGrid не выставляет свойство Header Background, он действительно имеет свойство для ColumnHeaderStyle. Используя технику, что DaniCE ранее предположил для отдельного столбца, что мы можем заменить шаблон заголовка для всех столбцов заголовка включая вакуум на правой стороне. Вниз сторона с заменой всего шаблона для заголовка - то, что мы теряем стрелки сортировки и разделители, которые присутствуют в шаблоне заголовка по умолчанию. К счастью, мы можем использовать шаблонный браузер, чтобы извлечь используемый шаблон по умолчанию и затем изменить копию его.

Здесь я бросил вместе быстрый пример, который изменит фон заголовков столбцов к LightBlue при хранении разделителей и сортировки. Смотрите на шаблон DataGridColumnHeader по умолчанию в шаблонном браузере, чтобы видеть, как иметь дело с изменением Фона, когда мышь нависает над ColumnHeader.

DataGrid Header Background

<data:DataGrid x:Name="grid">
    <data:DataGrid.ColumnHeaderStyle>
        <Style 
            xmlns:primitives="clr-namespace:System.Windows.Controls.Primitives;assembly=System.Windows.Controls.Data" 
            xmlns:vsm="clr-namespace:System.Windows;assembly=System.Windows"
            TargetType="primitives:DataGridColumnHeader" >
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="primitives:DataGridColumnHeader">
                        <Grid Name="Root">
                            <vsm:VisualStateManager.VisualStateGroups>
                                <vsm:VisualStateGroup x:Name="SortStates" >
                                    <vsm:VisualStateGroup.Transitions>
                                        <vsm:VisualTransition GeneratedDuration="00:00:0.1" />
                                    </vsm:VisualStateGroup.Transitions>
                                    <vsm:VisualState x:Name="Unsorted" />
                                    <vsm:VisualState x:Name="SortAscending">
                                        <Storyboard>
                                            <DoubleAnimation Storyboard.TargetName="SortIcon" Storyboard.TargetProperty="Opacity" Duration="0" To="1.0" />
                                        </Storyboard>
                                    </vsm:VisualState>
                                    <vsm:VisualState x:Name="SortDescending">
                                        <Storyboard>
                                            <DoubleAnimation Storyboard.TargetName="SortIcon" Storyboard.TargetProperty="Opacity" Duration="0" To="1.0" />
                                            <DoubleAnimation Storyboard.TargetName="SortIconTransform" Storyboard.TargetProperty="ScaleY" Duration="0" To="-.9" />
                                        </Storyboard>
                                    </vsm:VisualState>
                                </vsm:VisualStateGroup>
                            </vsm:VisualStateManager.VisualStateGroups>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="*" />
                                <RowDefinition Height="*" />
                                <RowDefinition Height="Auto" />
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto" />
                                <ColumnDefinition Width="*" />
                                <ColumnDefinition Width="Auto" />
                            </Grid.ColumnDefinitions>
                            <Rectangle x:Name="BackgroundRectangle" Stretch="Fill" Fill="LightBlue" Grid.ColumnSpan="2" Grid.RowSpan="2"  />
                            <ContentPresenter Grid.RowSpan="2" Content="{TemplateBinding Content}" Cursor="{TemplateBinding Cursor}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Margin="{TemplateBinding Padding}" />
                            <Rectangle Name="VerticalSeparator" Grid.RowSpan="2" Grid.Column="2" Width="1" VerticalAlignment="Stretch" Fill="{TemplateBinding SeparatorBrush}" Visibility="{TemplateBinding SeparatorVisibility}" />
                            <Path Grid.RowSpan="2" Name="SortIcon" RenderTransformOrigin=".5,.5" HorizontalAlignment="Left" VerticalAlignment="Center" Opacity="0" Grid.Column="1" Stretch="Uniform" Width="8" Data="F1 M -5.215,6.099L 5.215,6.099L 0,0L -5.215,6.099 Z ">
                                <Path.Fill>
                                    <SolidColorBrush Color="#FF444444" />
                                </Path.Fill>
                                <Path.RenderTransform>
                                    <TransformGroup>
                                        <ScaleTransform x:Name="SortIconTransform" ScaleX=".9" ScaleY=".9"  />
                                    </TransformGroup>
                                </Path.RenderTransform>
                            </Path>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </data:DataGrid.ColumnHeaderStyle>
</data:DataGrid>

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

7
ответ дан 5 December 2019 в 20:20
поделиться

Я придумал "чистое" решение .. Надеюсь, оно сработает для вас. Я просто переопределяю DataGrid и предоставляю метод GetTemplateChild. Используя его, вы можете получить доступ к DataGridColumnHeaderPresenter и содержащимся в нем DataGridColumnHeaders ...

1) Переопределить сетку данных

/// <summary>
/// Extends the DataGrid so that it's possible to access the template objects
/// </summary>
public class DataGridEx : System.Windows.Controls.DataGrid
{
    /// <summary>
    /// Exposes Template items
    /// </summary>
    public Object GetTemplateObject(String name)
    {
        return this.GetTemplateChild(name);
    }
}

2) Изменить фон

DataGridEx grid = new DataGridEx ();

... после шаблон применен ...

DataGridColumnHeadersPresenter obj = DataGrid.GetTemplateObject ("ColumnHeadersPresenter") as DataGridColumnHeadersPresenter;

DataGridColumnHeader h = obj.Children.Bor [0 ]20rushChildreader; Красный);

1
ответ дан 5 December 2019 в 20:20
поделиться
Другие вопросы по тегам:

Похожие вопросы: