WPF自己寫datagrid控件

        爲什麼不用系統自帶的datagrid控件呢,原因是列表標題是動態的,用系統自帶的控件一時我還沒想到怎麼解決,於是就想了一個辦法:自己動手寫datagrid控件,其實也很簡單。。。

預覽圖片

一、列表標題

(1)新建自定義標題控件:

<UserControl x:Class="SJZD.OverrideControl.Task_TaskNoListTitle"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" Loaded="UserControl_Loaded" 
             d:DesignHeight="50" d:DesignWidth="900">

   
        <Border x:Name="List_Border" Width="900"
                BorderBrush="#CFD6E0" BorderThickness="0">
            <Grid x:Name="grid" HorizontalAlignment="Stretch"></Grid>
        </Border>            
</UserControl>

後臺代碼:

using Newtonsoft.Json.Linq;
using SJZD.Code;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace SJZD.OverrideControl
{
    /// <summary>
    /// Task_TaskNoList.xaml 的交互邏輯
    /// </summary>
    public partial class Task_TaskNoListTitle : UserControl
    {
        JArray Cells;
        public Task_TaskNoListTitle(JArray cells)
        {
            InitializeComponent();
            Cells=cells;
        }


        private void Init()
        {
            System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                try
                {
                    Dispatcher.Invoke(new Action(() =>
                    {
                        if (Cells != null)
                        {
                            int colCount = Cells.Count;
                            for (int c = 0; c < colCount; c++)
                            {
                                ColumnDefinition col = new ColumnDefinition();                             
                                grid.ColumnDefinitions.Add(col);
                                Task_TaskNoListItem item = new Task_TaskNoListItem();                               
                                string title = JsonObjectConvert.GetObjectValue(Cells[c].ToString(), "title");
                                item.txName.Text = title;
                                if (title == "計劃數量" || title == "完成數量" || title == "次品數量" || title == "完成率" || title == "任務單號")
                                {
                                    col.Width =new GridLength(70, GridUnitType.Pixel);
                                }
                                if (title == "訂單編號")
                                {
                                    col.Width = new GridLength(100, GridUnitType.Pixel);
                                }
                                //設置樣式
                                Style myStyle = (Style)item.FindResource("TitleStyle");
                                item.txName.Style = myStyle;
                                grid.Children.Add(item);
                                Grid.SetColumn(item, c);
                            }
                        }
                        Cells = null;
                    }));
                }
                catch
                {

                }
            });
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            Init();
        }

    }
}
(2)Task_TaskNoListItem自定義控件:

<UserControl x:Class="SJZD.OverrideControl.Task_TaskNoListItem"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="35" d:DesignWidth="130">
    <UserControl.Resources>
        <Style  x:Key="ListStyle" TargetType="{x:Type Border}">
            <Setter Property="BorderBrush" Value="#CFD6E0"/>
            <Setter Property="BorderThickness" Value="0"/>
        </Style>
        <Style  x:Key="TitleStyle" TargetType="{x:Type TextBlock}">
            <Setter Property="FontSize" Value="15"/>
            <Setter Property="FontWeight" Value="Bold"/>
            <Setter Property="Foreground" Value="#575D75"/>
            <Setter Property="VerticalAlignment" Value="Center"/>
            <Setter Property="HorizontalAlignment" Value="Center"/>
        </Style>
        <Style  x:Key="TitleStyle1" TargetType="{x:Type TextBlock}">
            <Setter Property="FontSize" Value="13"/>          
            <Setter Property="Foreground" Value="#575D75"/>
            <Setter Property="VerticalAlignment" Value="Center"/>
            <Setter Property="HorizontalAlignment" Value="Center"/>
        </Style>
    </UserControl.Resources>
    <Border Grid.Column="1" Style="{StaticResource ListStyle}">
        <TextBlock x:Name="txName" Text="產品名稱" Style="{StaticResource TitleStyle1}"></TextBlock>
    </Border>
</UserControl>
 

後臺代碼:默認即可。

二、自定義內容控件:

<UserControl x:Class="SJZD.OverrideControl.Task_TaskNoListContent"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" Loaded="UserControl_Loaded" MouseLeftButtonUp="UserControl_MouseLeftButtonUp"
             d:DesignHeight="50" d:DesignWidth="900">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition Height="0"></RowDefinition>
        </Grid.RowDefinitions>
        <Border x:Name="List_Border" Height="35" Width="900">
            <Grid x:Name="grid"></Grid>
        </Border>
        <TextBlock x:Name="txRecordId" Visibility="Hidden"></TextBlock>
    </Grid>
</UserControl>
 

後臺代碼:

using Newtonsoft.Json.Linq;
using SJZD.Code;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace SJZD.OverrideControl
{
    /// <summary>
    /// Task_TaskNoListContent.xaml 的交互邏輯
    /// </summary>
    public partial class Task_TaskNoListContent : UserControl
    {
        JArray Cells;
        public Task_TaskNoListContent(JArray cells, string recordId = "")
        {
            InitializeComponent();
            Cells = cells;
            txRecordId.Text = recordId;
        }
        private void Init()
        {
            System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                try
                {
                    Dispatcher.Invoke(new Action(() =>
                    {
                        if (Cells != null)
                        {
                            int colCount = Cells.Count;
                            for (int c = 0; c < colCount; c++)
                            {
                                ColumnDefinition col = new ColumnDefinition();
                                grid.ColumnDefinitions.Add(col);
                                Task_TaskNoListItem item = new Task_TaskNoListItem();
                                item.txName.Text = JsonObjectConvert.GetObjectValue(Cells[c].ToString(), "value");
                                string title = JsonObjectConvert.GetObjectValue(Cells[c].ToString(), "title");
                                if (title == "計劃數量" || title == "完成數量" || title == "次品數量" || title == "完成率" || title == "任務單號")
                                {
                                    col.Width = new GridLength(66, GridUnitType.Pixel);
                                }
                                if (title == "訂單編號")
                                {
                                    col.Width = new GridLength(100, GridUnitType.Pixel);
                                }
                                grid.Children.Add(item);
                                Grid.SetColumn(item, c);
                            }
                        }
                        Cells = null;

                    }));
                }
                catch
                {

                }
            });
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            Init();
        }
        public event RoutedEventHandler Click;
        private void UserControl_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (Click != null)
            {
                Click(sender, e);
            }
        }
    }
}
三、使用:

後臺獲取數據並添加控件:

 //全部
        private void GetAllMacTaskData(string pageIndex)
        {
            try
            {
                Task_AllProduceInfo model = new Task_AllProduceInfo();
                model.txIndex.Text = pageIndex;
                int index = int.Parse(model.txIndex.Text);
                string webUrl = "v1/GET/getAllMacTaskList?macId=" + MachineId + "&pageIndex=" + index + "&pageSize=15&userId=" + ParaInfo.UserId;
                string json = GetgEndMacTaskData(webUrl);
                var data = JsonObjectConvert.GetData2JArray(json, "data");
                if (data != null)
                {
                    model.txCount.Text = JsonObjectConvert.GetObjectValue(json, "pageCount");//頁總數 
                    JArray cells = new JArray();
                    for (int i = 0; i < data.Count; i++)
                    {
                        cells = JsonObjectConvert.GetData2JArray(data[i].ToString(), "cells");
                        Task_TaskNoListContent contentList = new Task_TaskNoListContent(cells);
                        if (i % 2 != 0)
                        {
                            contentList.List_Border.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFF4FBF8"));
                        }
                        model.spContent.Children.Add(contentList);
                    }
                    Task_TaskNoListTitle list = new Task_TaskNoListTitle(cells);
                    model.bdTitle.Child = list;
                    model.PrePageClick += OnAllPageClick;
                    model.NextPageClick += OnAllPageClick;

                    TabContent3.Children.Clear();
                    TabContent3.Children.Add(model);
                }
            }
            catch (Exception ex)
            {

            }
        }

目前標題沒有做排序功能,其實擴展也不難,只需給標題項一個點擊事件即可。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章