我在使用一个组合框时遇到了麻烦。目标是:
ItemSource
是一个整数数组)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();
}
}
}