c# - 包含图像和数字的可编辑组合框
问题描述
我遇到了一个组合框的问题。目标是:
- Combo 必须是可编辑的并且它应该只接受数字(因为
ItemSource
它是一个整数数组) - Combo 显示 2 种信息:一种是显示预定义颜色的矩形,另一种是整数值
Colors
必须循环,除了索引为 0 的那个(例如,我们有 3 种颜色,如果用户输入 4,预期颜色是第二种,然后是第三种,然后是第二种,依此类推)- 输入数字时矩形应该是可见的并且颜色会改变
问题是,当我将组合更改IsEditable
为 true 时,不再遵循数据模板。它只是显示整数值。我正在使用转换器将整数转换为实际颜色,这部分似乎工作正常。
我现在不知道该怎么办。请帮忙。
XAML:
<Window x:Class="WPFCustomControls.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPFCustomControls"
Title="MainWindow" Height="350" Width="604">
<StackPanel>
<ComboBox
x:Name = "customControl"
Width = "Auto"
Height="Auto"
VerticalContentAlignment="Top"
VerticalAlignment="Stretch"
IsEditable="True">
<ComboBox.ItemsSource>
<Int32Collection>0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18</Int32Collection>
</ComboBox.ItemsSource>
<ComboBox.Resources>
<ResourceDictionary>
<local:IntToColorConverter x:Key="conv"/>
</ResourceDictionary>
</ComboBox.Resources>
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="0 0 0 2">
<Rectangle Width="28" Height="8" Fill="{Binding Converter={StaticResource conv}}" Stroke="#5C5A6B"/>
<TextBlock Margin="3 0 0 0" Text="Class "/>
<TextBlock Text="{Binding}"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</StackPanel>
</Window>
转换器:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;
namespace WPFCustomControls
{
public class IntToColorConverter : IValueConverter
{
static List<SolidColorBrush> Colors => new List<SolidColorBrush>()
{
new SolidColorBrush(Color.FromRgb( 0, 0, 0)),
new SolidColorBrush(Color.FromRgb(157, 157, 169)),
new SolidColorBrush(Color.FromRgb(231, 83, 92)),
};
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is int i && i >= 0)
{
if (i <= Colors.Count - 1)
return Colors[i];
return i % (Colors.Count - 1) == 0 ? Colors[Colors.Count - 1] : Colors[i % (Colors.Count - 1)];
}
return Colors[0];
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
解决方案
推荐阅读
- react-native - 无法解析模块'@babel/runtime/helpers/interoprequirewildcard' RN 0.61.5
- flutter - 缺少具体实现“getter Equatable”/道具问题
- javascript - Javascript 对象 - 映射对象和过滤器值
- sql - 我收到错误消息“错误:编码“WIN1251”的字节序列无效:0x00”
- arrays - 将数组转换为列表
- node.js - Sequelize Postgres createdAt time with timezone,以格式保存和获取日期和时间
- r - tidyverse:将不同长度的列组合到现有的小标题中
- jsf - java.lang.ClassCastException:org.primefaces.component.column.Column 不能转换为 org.primefaces.component.row.Row
- android - 使用 facebooks litho library 时应用程序在启动时崩溃
- c# - 在 C# 中禁用 USB 端口访问智能手机内存(无组策略)