wpf通过代码动态生成Label并通过popupcoloredit修改颜色

源码下载连接:https://download.csdn.net/download/weixin_43935474/12131658
在这里插入图片描述
我的一个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();//显示颜色编辑板面
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在ViewModel中通过按下Button来修改Label颜色,需要使用Command绑定和属性绑定。首先,在ViewModel中创建一个Command,用来处理Button的点击事件。然后,使用属性绑定将Button绑定到这个Command,以便在Button被点击时调用该命令。接下来,使用属性绑定将Label的前景色和命令的执行结果绑定在一起,这样Label颜色将会随着Button的点击而改变。以下是示例代码: ``` public class MyViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private ICommand _changeColorCommand; private Brush _labelColor; public MyViewModel() { _changeColorCommand = new RelayCommand(ChangeLabelColor); LabelColor = Brushes.Black; } public ICommand ChangeColorCommand { get { return _changeColorCommand; } } public Brush LabelColor { get { return _labelColor; } set { _labelColor = value; OnPropertyChanged("LabelColor"); } } private void ChangeLabelColor() { LabelColor = Brushes.Red; } protected void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } ``` 在XAML中,我们将Button和Label与ViewModel中的属性和命令绑定起来: ``` <Window.DataContext> <local:MyViewModel /> </Window.DataContext> <StackPanel> <Button Content="Change Label Color" Command="{Binding ChangeColorCommand}" /> <Label Content="Hello, WPF!" Foreground="{Binding LabelColor}" /> </StackPanel> ``` 现在当我们点击Button时,Label颜色将变为红色,正是我们在ViewModel中设置的颜色
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

GreenHandBruce

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值