WPF中为DataGrid设置行样式

WPF中我们可能会遇到这样的需求,就是需要为不同的行设置行样式,而不是统一的样式,实现方式主要分为两种。

第一种,通过代码设置行样式。首先选中datagrid控件,选择为控件添加loadingrow事件,接着再添加如下代码

  private void dataGridView1_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            int df = e.Row.GetIndex();
            if (df == 0)
            {
                e.Row.Height = 200;
                e.Row.Background = new SolidColorBrush(Colors.Red);//设置背景色透明
            }
            else if (df == 1)
            {
                e.Row.Height = 80;
                e.Row.Background = new SolidColorBrush(Colors.Blue);
                //e.Row.Padding = new Thickness(0,50,0,0);
            }
            else
            {
                e.Row.Height = 200;
                e.Row.Background = new SolidColorBrush(Colors.Green);
            }
        }

不过上面的方式有一定局限性,通常建议使用样式来实现,怎么实现,方式就是联想各行变色。这里需要注意的是,这两种方式不兼容,代码设置样式具有优先性。

<!--AlternationCount="3"-->
 <Style TargetType="DataGridRow">
        <Setter Property="Foreground" Value="Black" />
        <Style.Triggers>
            <!--隔行换色-->
            <Trigger Property="AlternationIndex" Value="0">
                <Setter Property="Height" Value="200" />
                <Setter Property="Background" Value="Transparent" />
            </Trigger>
            <Trigger Property="AlternationIndex" Value="1">
                <Setter Property="Height" Value="80" />
                <Setter Property="VerticalAlignment" Value="Bottom" />
                <Setter Property="Background" Value="AliceBlue" />
            </Trigger>
            <Trigger Property="AlternationIndex" Value="2">
                <Setter Property="Height" Value="200" />
                <Setter Property="Background" Value="Transparent" />
            </Trigger>
        </Style.Triggers>
    </Style>
发布了120 篇原创文章 · 获赞 50 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/u014650759/article/details/101621995