wpf DataGrid的使用

利用DataGrid

直接上干货!!!!!

    public class LogMgr {

        #region 单例
        private static Lazy<LogMgr> inst = new Lazy<LogMgr>(() => new LogMgr(), true);
        public static LogMgr Inst => inst.Value;

        private LogMgr() {
            LogInfos = new ObservableCollection<LogInfo>()
            {
                new LogInfo()
                {
                    Time = DateTime.Now.ToString("HH:mm:ss.fff"),
                    Message = "软件启动",
                    FontColor = "Green",
                }
            };
        }
        #endregion
        public ObservableCollection<LogInfo> LogInfos { get; set; }

        public void ShowLog(string message, string fontColor = "Black", int maxCount = 100) {
            var info = typeof(Brushes).GetProperties().Any(k => k.Name == fontColor);
            System.Windows.Application.Current.Dispatcher.Invoke(() => {
                LogInfos.Add(new LogInfo() { Time = DateTime.Now.ToString("HH:mm:ss.fff"), Message = message, FontColor = fontColor });
                if (LogInfos.Count > maxCount) {
                    LogInfos.RemoveAt(0);
                }
            });
        }
        /// <summary>
        /// 绑定datagrid控件用于显示log
        /// </summary>
        /// <param name="dataGrid"></param>
        /// <param name="fontSize"></param>
        /// <param name="MinWidth"></param>
        public void BindDataGrid(DataGrid dataGrid, double fontSize = 20, double MinWidth = 150) {

            dataGrid.AutoGenerateColumns = false;
            dataGrid.GridLinesVisibility = DataGridGridLinesVisibility.None;
            dataGrid.ItemsSource = this.LogInfos;

            DataTemplate dataTemplate1 = new DataTemplate();
            DataTemplate dataTemplate2 = new DataTemplate();

            DataGridTemplateColumn dataGridColumn1 = new DataGridTemplateColumn();
            DataGridTemplateColumn dataGridColumn2 = new DataGridTemplateColumn();

            FrameworkElementFactory textBlockIconFactory1 = new FrameworkElementFactory(typeof(TextBlock));
            textBlockIconFactory1.SetValue(TextBlock.FontSizeProperty, fontSize);
            textBlockIconFactory1.SetValue(TextBlock.MinWidthProperty, MinWidth);
            textBlockIconFactory1.SetValue(TextBlock.HorizontalAlignmentProperty, HorizontalAlignment.Center);
            textBlockIconFactory1.SetValue(TextBlock.VerticalAlignmentProperty, VerticalAlignment.Center);
            textBlockIconFactory1.SetBinding(TextBlock.TextProperty, new Binding("Time") { UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged, Mode = BindingMode.TwoWay });
            textBlockIconFactory1.SetBinding(TextBlock.ForegroundProperty, new Binding("FontColor") { UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged, Mode = BindingMode.TwoWay });
            dataTemplate1.VisualTree = textBlockIconFactory1;

            FrameworkElementFactory textBlockIconFactory2 = new FrameworkElementFactory(typeof(TextBlock));
            textBlockIconFactory2.SetValue(TextBlock.FontSizeProperty, fontSize);
            textBlockIconFactory2.SetValue(TextBlock.MinWidthProperty, MinWidth);
            textBlockIconFactory2.SetValue(TextBlock.HorizontalAlignmentProperty, HorizontalAlignment.Center);
            textBlockIconFactory2.SetValue(TextBlock.VerticalAlignmentProperty, VerticalAlignment.Center);
            textBlockIconFactory2.SetBinding(TextBlock.TextProperty, new Binding("Message") { UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged, Mode = BindingMode.TwoWay });
            textBlockIconFactory2.SetBinding(TextBlock.ForegroundProperty, new Binding("FontColor") { UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged, Mode = BindingMode.TwoWay });
            dataTemplate2.VisualTree = textBlockIconFactory2;

            dataGridColumn1.CellTemplate = dataTemplate1;
            dataGridColumn2.CellTemplate = dataTemplate2;
            dataGridColumn1.Header = "Time";
            dataGridColumn1.Width = DataGridLength.Auto;




            dataGridColumn2.Header = "Message";
            dataGridColumn2.Width = DataGridLength.Auto;
            dataGrid.Columns.Add(dataGridColumn1);
            dataGrid.Columns.Add(dataGridColumn2);
            ///设置标题居中
            dataGrid.ColumnHeaderStyle = new Style(typeof(DataGridColumnHeader)) {
                Setters =
                {
                    new Setter()
                    {
                        Property = DataGridColumnHeader.HorizontalContentAlignmentProperty,Value = HorizontalAlignment.Center
                    },
                },
                
            };
            dataGrid.RowHeaderStyle=new Style(typeof(DataGridRowHeader))
            {
                Setters =
                {
                    
                    new Setter()
                    {
                        Property = DataGridColumnHeader.BorderThicknessProperty,Value = new Thickness(0),
                    },
                    new Setter()
                    {
                        Property = DataGridColumnHeader.BackgroundProperty,Value = Brushes.Transparent,
                    },
                    new Setter()
                    {
                        Property = DataGridColumnHeader.FontSizeProperty,Value = 30.0,
                    },
                }
            };
            dataGrid.LoadingRow += (object sender, DataGridRowEventArgs e) => {
                e.Row.Header = (e.Row.GetIndex()+1).ToString();
            };
        }


    }

    public class LogInfo : INotifyPropertyChanged {
        public event PropertyChangedEventHandler PropertyChanged;
        private string time;
        private string message;
        private string fontColor = "Black";
        public string Time {
            get { return time; }
            set { time = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Time")); }
        }

        public string Message {
            get { return message; }
            set { message = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Message")); }
        }
        public string FontColor {
            get { return fontColor; }
            set {
                fontColor = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("FontColor"));
            }
        }
    }

datagrid 扩展方法封装(用于显示日志)

  public static class LogExtension
    {
        /*public*/ static ObservableCollection<LogInfo> LogInfos { get; set; }=new ObservableCollection<LogInfo>();

        public static void ShowLog(string message, string fontColor = "Black", int maxCount = 100)
        {
            var info = typeof(Brushes).GetProperties().Any(k => k.Name == fontColor);
            System.Windows.Application.Current.Dispatcher.Invoke(() => {
                LogInfos.Add(new LogInfo() { Time = DateTime.Now.ToString("HH:mm:ss.fff"), Message = message, FontColor = fontColor });
                if (LogInfos.Count > maxCount)
                {
                    LogInfos.RemoveAt(0);
                }
            });
        }
        public static void IsShowLog( this DataGrid dataGrid, double fontSize = 20, double MinWidth = 150)
        {
            dataGrid.AutoGenerateColumns = false;
            dataGrid.GridLinesVisibility = DataGridGridLinesVisibility.None;
            dataGrid.ItemsSource = LogExtension.LogInfos;

            DataTemplate dataTemplate1 = new DataTemplate();
            DataTemplate dataTemplate2 = new DataTemplate();

            DataGridTemplateColumn dataGridColumn1 = new DataGridTemplateColumn();
            DataGridTemplateColumn dataGridColumn2 = new DataGridTemplateColumn();

            FrameworkElementFactory textBlockIconFactory1 = new FrameworkElementFactory(typeof(TextBlock));
            textBlockIconFactory1.SetValue(TextBlock.FontSizeProperty, fontSize);
            textBlockIconFactory1.SetValue(TextBlock.MinWidthProperty, MinWidth);
            textBlockIconFactory1.SetValue(TextBlock.HorizontalAlignmentProperty, HorizontalAlignment.Center);
            textBlockIconFactory1.SetValue(TextBlock.VerticalAlignmentProperty, VerticalAlignment.Center);
            textBlockIconFactory1.SetBinding(TextBlock.TextProperty, new Binding("Time") { UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged, Mode = BindingMode.TwoWay });
            textBlockIconFactory1.SetBinding(TextBlock.ForegroundProperty, new Binding("FontColor") { UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged, Mode = BindingMode.TwoWay });
            dataTemplate1.VisualTree = textBlockIconFactory1;

            FrameworkElementFactory textBlockIconFactory2 = new FrameworkElementFactory(typeof(TextBlock));
            textBlockIconFactory2.SetValue(TextBlock.FontSizeProperty, fontSize);
            textBlockIconFactory2.SetValue(TextBlock.MinWidthProperty, MinWidth);
            textBlockIconFactory2.SetValue(TextBlock.HorizontalAlignmentProperty, HorizontalAlignment.Left);
            textBlockIconFactory2.SetValue(TextBlock.VerticalAlignmentProperty, VerticalAlignment.Center);
            textBlockIconFactory2.SetBinding(TextBlock.TextProperty, new Binding("Message") { UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged, Mode = BindingMode.TwoWay });
            textBlockIconFactory2.SetBinding(TextBlock.ForegroundProperty, new Binding("FontColor") { UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged, Mode = BindingMode.TwoWay });
            dataTemplate2.VisualTree = textBlockIconFactory2;

            dataGridColumn1.CellTemplate = dataTemplate1;
            dataGridColumn2.CellTemplate = dataTemplate2;
            dataGridColumn1.Header = "Time";
            dataGridColumn1.Width = DataGridLength.Auto;

            dataGridColumn2.Header = "Message";
            dataGridColumn2.Width = DataGridLength.Auto;
            dataGrid.Columns.Add(dataGridColumn1);
            dataGrid.Columns.Add(dataGridColumn2);
            ///设置标题居中
            dataGrid.ColumnHeaderStyle = new Style(typeof(DataGridColumnHeader))
            {
                Setters =
                {
                    new Setter()
                    {
                        Property = DataGridColumnHeader.HorizontalContentAlignmentProperty,Value = HorizontalAlignment.Center
                    },
                },

            };
            dataGrid.RowHeaderStyle = new Style(typeof(DataGridRowHeader))
            {
                Setters =
                {

                    new Setter()
                    {
                        Property = DataGridColumnHeader.BorderThicknessProperty,Value = new Thickness(0),
                    },
                    new Setter()
                    {
                        Property = DataGridColumnHeader.BackgroundProperty,Value = Brushes.Transparent,
                    },
                    new Setter()
                    {
                        Property = DataGridColumnHeader.FontSizeProperty,Value = 30.0,
                    },
                }
            };
            dataGrid.LoadingRow += (object sender, DataGridRowEventArgs e) => {
                e.Row.Header = (e.Row.GetIndex() + 1).ToString();
            };
        }
    }

使用方法


    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            dg1.IsShowLog();
            LogExtension.ShowLog("soft start1!", "Red");
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
           
            var colors = typeof(Brushes).GetProperties().Select(k => k.Name).ToList();
            for (int i = 0; i < 10; i++)
            {
                int index = new Random().Next(0, colors.Count);
                LogExtension.ShowLog($"{index}==>{colors[index]}", colors[index]);
                Debug.WriteLine($"{index}==>{colors[index]}");
            }

        }
    }

效果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LEO20210522

求打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值