WPF中为DataGrid设置行样式

WPF中为DataGrid设置行样式WPF中我们可能会遇到这样的需求,就是需要为不同的行设置行样式,而不是统一的样式,实现方式主要分为两种。第一种,通过代码设置行样式。首先选中datagrid控件,选择为控件添加loadingrow事件,接着再添加如下代码privatevoiddataGridView1_LoadingRow(objectsender,DataGridRowEventArgse)…

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>

 

今天的文章WPF中为DataGrid设置行样式分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/28578.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注