首页 > 其他分享 >wpf VS2017 带图片显示的自定义Combox

wpf VS2017 带图片显示的自定义Combox

时间:2022-11-03 11:25:35浏览次数:45  
标签:自定义 Combox VS2017 object System value stringArray using public

先看下效果图

 

 思路大概是将ComboxItem分为4列,然后将下拉框选中的值设置到Combox中

首先新建一个wpf的工程,取名为PictureCombox

1.添加需要用的png图,先导入图片两张,取名0.png和1.png(这个用画图板随便画都可以的,然后放到工程目录中,导入到工程里面)

2.添加一个绑定属性的类,文件为CbbData.cs,代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PictureCombox
{
    class CbbData
    {
        public string data1 { get; set; }

        public string data2 { get; set; }

        public string dataAll { get; set; }

        public string ImgNameLeft { get; set; }

        public string ImgNameRight { get; set; }
    }
}
View Code

3.添加一个图片转换器类ImageConverter.cs文件,代码如下:

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Media.Imaging;

namespace PictureCombox
{
    class ImageConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return null;
            string imgName = value.ToString();

            if (imgName == "")
                return null;

            BitmapImage bitmap = CreateBitmap.GetBitmap(imgName);
            return bitmap;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    class ImageLeftConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null )
                return null;

            string imgName = value.ToString();

            if (imgName == "")
                return null;

            string[] stringArray = imgName.Split(",".ToCharArray());

            stringArray[0] = (int.Parse(stringArray[0]) % 2).ToString();
            
            BitmapImage bitmap = CreateBitmap.GetBitmap(stringArray[0]);
            return bitmap;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    class ImageRightConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return null;

            string imgName = value.ToString();

            if (imgName == "")
                return null;

            string[] stringArray = imgName.Split(",".ToCharArray());

            if (stringArray.Length > 1)
            {
                stringArray[1] = (int.Parse(stringArray[1]) % 2).ToString();
                BitmapImage bitmap = CreateBitmap.GetBitmap(stringArray[1]);
                return bitmap;
            }
            else
            {
                stringArray[0] = (int.Parse(stringArray[0]) % 2).ToString();
                BitmapImage bitmap = CreateBitmap.GetBitmap(stringArray[0]);
                return bitmap;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    class ComboxLeftStringConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return null;

            string strAll = value.ToString();

            string[] stringArray = strAll.Split(",".ToCharArray());

            String stringTarget = String.Format("{0,-3}", stringArray[0]);

            return stringTarget;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    class ComboxRightStringConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return null;

            string strAll = value.ToString();

            string[] stringArray = strAll.Split(",".ToCharArray());

            String stringTarget;

            if (stringArray.Length > 1)
            {
                stringTarget = String.Format("{0,-3}", stringArray[1]);
            }
            else
            {
                stringTarget = String.Format("{0,-3}", stringArray[0]);
            }

            return stringTarget;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
View Code

4.添加一个CreateBitmap.cs文件,代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;

namespace PictureCombox
{
    class CreateBitmap
    {
        public static BitmapImage GetBitmap(string name)
        {
            BitmapImage bitmap;
            string rootPath = @"pack://application:,,,/" + name + ".png";
            bitmap = new BitmapImage(new Uri(rootPath, UriKind.Absolute));
            return bitmap;
        }
    }
}
View Code

5.最后再添加资源文件CustomDictionary.xaml,代码如下:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:PictureCombox">
    
    <local:ImageConverter x:Key="ImageConverter"/>
    <local:ImageLeftConverter x:Key="ImageLeftConverter"/>
    <local:ImageRightConverter x:Key="ImageRightConverter"/>
    
    <local:ComboxLeftStringConverter x:Key="ComboxLeftStringConverter"/>
    <local:ComboxRightStringConverter x:Key="ComboxRightStringConverter"/>
    
    <ControlTemplate x:Key="MyComboBoxItem"
                         TargetType="ComboBoxItem">
        <Grid Background="{TemplateBinding Background}"
                  >
            <Border x:Name="itemBorder"
                        BorderThickness="{TemplateBinding BorderThickness}"
                        BorderBrush="Red"
                        Background="LightBlue"
                        Height="40"
                        >
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*"></ColumnDefinition>
                        <ColumnDefinition Width="*"></ColumnDefinition>
                        <ColumnDefinition Width="*"></ColumnDefinition>
                        <ColumnDefinition Width="*"></ColumnDefinition>
                    </Grid.ColumnDefinitions>
                    
                    <Image Grid.Column="0" Margin="3" Source="{Binding ImgNameLeft,Converter={StaticResource ImageConverter}}"/>
                    <!--<Path Grid.Column="0" Stroke="Black" StrokeThickness="2" Margin="5" Data="M 0,0  L 0,25  L 25,25  L 25,0 Z"/>-->

                    <TextBlock Grid.Column="1" Text="{Binding data1}" 
                                   Margin="0,0,0,0"
                                   HorizontalAlignment="Left"
                                   VerticalAlignment="Center"
                                   TextAlignment="Center"/>
                    
                    <Image Grid.Column="2" Margin="4" Source="{Binding ImgNameRight,Converter={StaticResource ImageConverter}}"/>
                    <!--<Path Grid.Column="2" Stroke="Black" StrokeThickness="2" Margin="5" Data="M 12,12 A 10,10 0 1 1 12,11.9 Z"/>
                    <Path Grid.Column="2" Stroke="Black" StrokeThickness="2" Margin="0,0,0,0" Data="M 7,5 L 7,30"/>-->

                    <TextBlock Grid.Column="3" Text="{Binding data2}" 
                                   Margin="0,0,0,0"
                                   HorizontalAlignment="Left"
                                   VerticalAlignment="Center"
                                   TextAlignment="Center"/>
                </Grid>
            </Border>
        </Grid>
        <ControlTemplate.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter TargetName="itemBorder"
                            Property="Background"
                            Value="Gray"/>
                <Setter TargetName="itemBorder"
                            Property="BorderBrush"
                            Value="Blue"/>
            </Trigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>

    <ControlTemplate x:Key="MyToggleBtnStyle" 
                         TargetType="ToggleButton">
        <Border Name="MyBorder"
                    Background="AliceBlue"
                    BorderThickness="1" 
                    BorderBrush="Transparent">
            <Path Name="MyPath"
                      Fill="Red"
                      Height="10"
                      Width="10"
                      Data="M5,5 L10,10 L15,5 z"                      
                      Stretch="Fill">
            </Path>
        </Border>
        <ControlTemplate.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter TargetName="MyPath" Property="Fill" Value="Green"></Setter>
                <Setter TargetName="MyBorder" Property="Background" Value="White"></Setter>
            </Trigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>

    <Style x:Key="MyCbbStyle" TargetType="ComboBox">
        <Setter Property="ItemContainerStyle">
            <Setter.Value>
                <Style TargetType="ComboBoxItem">
                    <Setter Property="FontSize" Value="30"/>
                    <Setter Property="Foreground" Value="Blue"/>
                    <Setter Property="Template"
                                Value="{StaticResource MyComboBoxItem}"/>
                </Style>
            </Setter.Value>
        </Setter>

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ComboBox">
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="7*"/>
                            <ColumnDefinition Width="3*" MaxWidth="20"/>
                        </Grid.ColumnDefinitions>

                        <Border Grid.Column="0"
                                    BorderBrush="Blue"
                                    BorderThickness="1,1,0,1"
                                    Background="AliceBlue">
                            <ToggleButton Name="togglebutton" Background="{TemplateBinding Background}" VerticalAlignment="Stretch"
                                      Foreground="{TemplateBinding Foreground}"                                     
                                      BorderBrush="#FF045B32" BorderThickness="0"                                      
                                      FontSize="{TemplateBinding FontSize}"                                    
                                      HorizontalContentAlignment="Left"                                   
                                      IsTabStop="False"
                                      Focusable="False"
                                      IsChecked="{Binding Path=IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}" ClickMode="Press">
                                <Grid  Height="{Binding Path=ActualHeight, ElementName=togglebutton}"
                                        Width="{Binding Path=ActualWidth, ElementName=togglebutton}">
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="*"></ColumnDefinition>
                                        <ColumnDefinition Width="*"></ColumnDefinition>
                                        <ColumnDefinition Width="*"></ColumnDefinition>
                                        <ColumnDefinition Width="*"></ColumnDefinition>
                                    </Grid.ColumnDefinitions>

                                    <Image Grid.Column="0" Source="{TemplateBinding Text,Converter={StaticResource ImageLeftConverter}}"/>
                                    <!--<Path Grid.Column="0" Stroke="Black" StrokeThickness="2" Margin="5" Data="M 0,0  L 0,25  L 25,25  L 25,0 Z"/>-->

                                    <TextBlock Grid.Column="1" Text="{TemplateBinding Text, Converter={StaticResource ComboxLeftStringConverter}}" 
                                       Margin="0,0,0,0"
                                       HorizontalAlignment="Left"
                                       VerticalAlignment="Center"
                                       TextAlignment="Center"/>

                                    <Image Grid.Column="2"  Source="{TemplateBinding Text,Converter={StaticResource ImageRightConverter}}"/>
                                    <!--<Path Grid.Column="2" Stroke="Black" StrokeThickness="2" Margin="5" Data="M 12,12 A 10,10 0 1 1 12,11.9 Z"/>
                                    <Path Grid.Column="2" Stroke="Black" StrokeThickness="2" Margin="0,0,0,0" Data="M 7,5 L 7,30"/>-->

                                    <TextBlock Grid.Column="3" Text="{TemplateBinding Text, Converter={StaticResource ComboxRightStringConverter}}" 
                                       Margin="0,0,0,0"
                                       HorizontalAlignment="Left"
                                       VerticalAlignment="Center"
                                       TextAlignment="Center"/>
                                </Grid>
                            </ToggleButton>
                        </Border>
                        <Border Grid.Column="1"
                                    BorderBrush="Red"
                                    BorderThickness="1">
                            <ToggleButton IsChecked="{Binding Path=IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
                                              ClickMode="Press"
                                              Template="{StaticResource MyToggleBtnStyle}"></ToggleButton>
                        </Border>
                        <Popup Name="MyPopup"
                                   IsOpen="{TemplateBinding IsDropDownOpen}"
                                   Placement="Bottom">
                            <Border MinWidth="{TemplateBinding ActualWidth}"
                                        MaxHeight="{TemplateBinding MaxDropDownHeight}">
                                <ScrollViewer MaxHeight="{TemplateBinding MaxDropDownHeight}"
                                                  HorizontalScrollBarVisibility="Auto"
                                                  VerticalScrollBarVisibility="Auto">
                                    <StackPanel Background="AliceBlue"
                                                    IsItemsHost="True"
                                                    />

                                </ScrollViewer>
                            </Border>
                        </Popup>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>
View Code

引用外部资源文件,其命名空间应与工程保持一致,如果还是找不到的话,需要在App.xaml中添加如下代码:

<Application x:Class="PictureCombox.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:PictureCombox"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="CustomDictionary.xaml"></ResourceDictionary>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>
View Code

MainWindow.xaml代码

<Window x:Class="PictureCombox.MainWindow"
        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:PictureCombox"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <ComboBox Name="myCbb" DisplayMemberPath="dataAll" Style="{StaticResource MyCbbStyle}" Height="60" Width="250" HorizontalAlignment="Left" VerticalAlignment="Top" SelectedIndex="2"/>
    </Grid>
</Window>
View Code

MainWindow.xaml.cs代码

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 PictureCombox
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            List<CbbData> cbbDatas = new List<CbbData>();
            for (int i = 0; i < 20; i++)
            {
                CbbData cbbData = new CbbData();
                cbbData.data1 = (i + 1).ToString();
                cbbData.data2 = (i + 2).ToString();
                cbbData.dataAll = (i + 1).ToString() + "," + (i + 2).ToString();
                cbbData.ImgNameLeft = "0";
                cbbData.ImgNameRight = "1";
                cbbDatas.Add(cbbData);
            }

            myCbb.ItemsSource = cbbDatas;
        }
    }
}
View Code

 

标签:自定义,Combox,VS2017,object,System,value,stringArray,using,public
From: https://www.cnblogs.com/wuguoqiang/p/16853816.html

相关文章

  • 全局Loading(自定义Loading)
    在调用的方法中加入(中间注释部分,为请求数据方法,结束都需要关闭loading)constloading=this.$loading({lock:true,text:'正在努力加载数据中,请耐......
  • 手把手教你用DevExpress WinForm添加和自定义工具栏皮肤选择器
    DevExpressWinForm拥有180+组件和UI库,能为WindowsForms平台创建具有影响力的业务解决方案。DevExpressWinForms能完美构建流畅、美观且易于使用的应用程序,无论是Office......
  • django中间件以及自定义中间件
    middleware中间件就是在目标和结果之间进行的额外处理过程,在Django中就是request和response之间进行的处理,相对来说实现起来比较简单,但是要注意它是对全局有效的,可以在全......
  • Struts2自定义方法最佳实践
    自定义方法实现在struts.xml配置method,并且在对应的Action实现对应方法即可。struts.xml<actionname="login2"class="space.terwer.struts23.LoginAction2"met......
  • 博客园自定义主题中添加迷你音乐插件
    说明:这里直接介绍最简单直接的一种设置方式,想深入了解,自己DIY的,可滑到本文底部,附有其他大佬的方案。首先,进入你的博客园后台设置,在开通了JS权限(可自定义博客园主......
  • vim指令diffopt:Vimdiff比较文本时自定义差异上下文要显示的行数
    Vim相关指令:在Vim窗口执行setdiffopt=filler,context:10或setdiffopt=filler,context:0命令即可(其中10为山下文的行数,设置为0即仅显示差异文本,不显示任何相当的行......
  • 自定义的组件无法显示;
      定义了一个自定义组件title,但是无论如何都显示不出来,看了title组件的created()函数的打印,也灭有打印; 调试的话,看到title组件也没有像其他组件一样通过re......
  • SpringBoot自定义注解+异步+观察者模式实现业务日志保存
    一、前言我们在企业级的开发中,必不可少的是对日志的记录,实现有很多种方式,常见的就是基于AOP+注解进行保存,但是考虑到程序的流畅和效率,我们可以使用异步进行保存,在高并发情......
  • 树莓派搭建WordPress博客:解析自定义域名 9/10
    上一篇​​树莓派搭建WordPress博客:更换WordPress主体模板8/10​​在之前的系列文章中,我们向大家介绍了如何在本地树莓派上搭建属于自己的网站,并让这个网站能被公众互联网......
  • 企业级自定义表单引擎解决方案(十六)--Excel导入导出
    Excel对于后端管理系统来说,永远都是绕不开的话题,开发Excel导入导出功能往往都比较麻烦,因为涉及到Excel导入模板制作、Excel表格数据与系统数据库表字段映射、Excel导入......