天天看點

wpf通過代碼動态生成Label并通過popupcoloredit修改顔色

源碼下載下傳連接配接:https://download.csdn.net/download/weixin_43935474/12131658

wpf通過代碼動态生成Label并通過popupcoloredit修改顔色

我的一個WPF項目上有個功能:

需要用到動态生成Label并為其添加事件響應函數,

同時需要用到PopupColorEdit修改Label的顔色。

研究了一天,在此記錄一下:

主界面的MainWindow.xaml代碼如下:

<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:TestWPFColorEdit"
        xmlns:dxe="http://schemas.devexpress.com/winfx/2008/xaml/editors" x:Class="TestWPFColorEdit.MainWindow"
        mc:Ignorable="d"
        Title="MainWindow" Height="119.434" Width="530">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="1*"/>
            <RowDefinition Height="1*"/>
        </Grid.RowDefinitions>
        <Border BorderThickness="1" BorderBrush="#FF737070">
            <DockPanel Name="myDockPanel" LastChildFill="False" Margin="1" Width="520"/>
        </Border>
        <dxe:PopupColorEdit Grid.Row="1"  Name="myPopUpColorEdit" HorizontalAlignment="Left" Margin="365,0,0,0" VerticalAlignment="Top" Width="150" Height="26"/>
        <TextBox Grid.Row="1" x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="158,0,0,0" TextWrapping="Wrap" Text="1" VerticalAlignment="Top" Width="71" TextChanged="textBox_TextChanged"/>
        <Label Grid.Row="1"  x:Name="label" HorizontalAlignment="Left" Margin="10,0,0,0" VerticalAlignment="Top" Content="色标尺分割段數(&lt;20)" Width="143" Height="26"/>
    </Grid>
</Window>
           

MainWindow.xaml.cs檔案代碼如下:

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;

namespace TestWPFColorEdit
{
    /// <summary>
    /// MainWindow.xaml 的互動邏輯
    /// </summary>
    public partial class MainWindow : Window
    {
        private int nColorLabelNum = 0;//表示目前有幾個label
        private int nCurrentLabelID = -1;//目前使用者輕按兩下的那個label的ID
        public struct RulerColor//用來記錄Label中的顔色
        {
            byte R;
            byte G;
            byte B;
            public RulerColor(byte r, byte g, byte b)
            {
                R = r;
                G = g;
                B = b;
            }
        }
        private List<RulerColor> lstColor;//用來記錄界面上所有Label中的顔色
        public Dictionary<int, Label> dicColorLabel;//用來存放Label引用和其ID
        public MainWindow()
        {
            lstColor = new List<RulerColor>();
            dicColorLabel = new Dictionary<int, Label>();
            InitializeComponent();
            myPopUpColorEdit.ColorChanged += MyPopUpColorEdit_ColorChanged;//使用者在顔色編輯闆中點選顔色後會觸發該ColorChanged事件,将該事件綁定到下面的MyPopUpColorEdit_ColorChanged()函數
        }

        private void MyPopUpColorEdit_ColorChanged(object sender, RoutedEventArgs e)
        {
            byte R = myPopUpColorEdit.Color.R;
            byte G = myPopUpColorEdit.Color.G;
            byte B = myPopUpColorEdit.Color.B;
            if (nCurrentLabelID != -1 && nCurrentLabelID < dicColorLabel.Count)
            {
                System.Windows.Media.Color col = System.Windows.Media.Color.FromArgb(255, R, G, B);
                dicColorLabel[nCurrentLabelID].Background = new SolidColorBrush(col);
                lstColor[nCurrentLabelID] = new RulerColor(R, G, B);
            }
        }
        private void textBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            Regex rx = new Regex("^[0-9]*$");
            if (!rx.IsMatch(textBox.Text))//不是整數
            {
                return;
            }
            string str = textBox.Text.ToString();
            if (str == "")
            {
                return;
            }
            nColorLabelNum = Convert.ToInt32(str);
            if(nColorLabelNum>20)
            {
                return;
            }
            if (dicColorLabel != null && dicColorLabel.Count > 0)
            {
                int nCount = dicColorLabel.Count;
                for (int i = 0; i < nCount; i++)
                {
                    dicColorLabel[i] = null;
                }
                dicColorLabel.Clear();
                myDockPanel.Children.Clear();

            }
            if (lstColor.Count > 0)
            {
                lstColor.Clear();
                //lstColor = null;//如果讓lstColor = null,則後面需要用到lstColor的時候必須重新new
            }
            for (int i = 0; i < nColorLabelNum; i++)
            {
                byte B = Convert.ToByte(50 + i * 10);
                Label label = new Label();
                label.MouseDoubleClick += Label_MouseDoubleClick;
                System.Windows.Media.Color col = System.Windows.Media.Color.FromArgb(255, 0, B, 0);
                label.Background = new SolidColorBrush(col);
                lstColor.Add(new RulerColor(0, 0, B));
                label.Width = (myDockPanel.Width-8)*1.0f / nColorLabelNum-2;
                label.Margin = new Thickness(1,0,1,0);
                //将label添加到myDockPanel上
                IAddChild container = myDockPanel;//建立一個容器,将panel賦給他
                container.AddChild(label);//将label按鈕添加到panel中
                dicColorLabel.Add(i, label);
            }
        }

        private void Label_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            Label mlabel = (Label)sender;
            for (int i = 0; i < dicColorLabel.Count; i++)
            {
                if (dicColorLabel[i] == mlabel)//找到使用者輕按兩下的label在dicColorLabel字典中的key(即label的ID号)
                {
                    nCurrentLabelID = i;
                }
            }
            myPopUpColorEdit.ShowPopup();//顯示顔色編輯闆面
        }
    }
}