c# – 在ComboBox中获取所选项

好的,所以我有一个ComboBox,里面装有ComboBoxItem,里面包含一个带有填充字段的矩形内容:

<ComboBox x:Name="comboBox" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Height="70" Width="100">
    <ComboBoxItem IsSelected="True">
        <ComboBoxItem.Content>
            <Rectangle Fill="#8BC34A" Width="50" Height="50"/>
        </ComboBoxItem.Content>
    </ComboBoxItem>
    <ComboBoxItem>
        <Rectangle Fill="#7CB342" Width="50" Height="50"/>
    </ComboBoxItem>
    <ComboBoxItem>
        <Rectangle Fill="#689F38" Width="50" Height="50"/>
    </ComboBoxItem>
    <ComboBoxItem>
        <Rectangle Fill="#558B2F" Width="50" Height="50"/>
    </ComboBoxItem>
    <ComboBoxItem>
        <Rectangle Fill="#33691E" Width="50" Height="50"/>
    </ComboBoxItem>
</ComboBox>

我需要从Rectangle的Fill中获取一个Brush(或者至少是Fill的字符串值).所以我尝试了这个:

var comboBoxItem = comboBox.Items[comboBox.SelectedIndex] as ComboBoxItem;
var cmb = comboBoxItem.Content as Windows.UI.Xaml.Shapes.Rectangle;

然后通过cmd.Fill获取Fill,但我得到一个null异常.

那我该怎么办呢?我需要它从ComboBox的选定值中着色.谢谢!

最佳答案 我不确定你为什么在组合框的内容中得到null.但是,如果你这样做应该工作:

<ComboBox x:Name="comboBox" SelectedIndex="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Height="70" Width="100">
    <Rectangle Fill="#8BC34A" Width="50" Height="50"/>
    <Rectangle Fill="#7CB342" Width="50" Height="50"/>
    <Rectangle Fill="#689F38" Width="50" Height="50"/>
    <Rectangle Fill="#558B2F" Width="50" Height="50"/>
    <Rectangle Fill="#33691E" Width="50" Height="50"/>
</ComboBox>

然后你可以简单地将所选项目转换为Rectangle:

var selectedRectangle = comboBox.Items[comboBox.SelectedIndex] as Rectangle;
var selectedRectangle = comboBox.SelectedItem as Rectangle;

请注意,通常ComboBox使用ItemsSource和ItemTemplate,在这种情况下,您的代码可能如下所示:

<ComboBox x:Name="comboBox" SelectedIndex="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Height="70" Width="100">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <Rectangle Fill="{Binding Converter={StaticResource StringToBrushConverter}}" Width="50" Height="50"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
    <x:String>FF8BC34A</x:String>
    <x:String>FF7CB342</x:String>
    <x:String>FF689F38</x:String>
    <x:String>FF558B2F</x:String>
</ComboBox>

和转换器:

public class StringToBrushConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        string color = (string)value;
        byte[] bytes = new byte[4];
        for (int i = 0; i < color.Length; i += 2)
            bytes[i / 2] = byte.Parse(color.Substring(i, 2), NumberStyles.HexNumber);

        return new SolidColorBrush(Color.FromArgb(bytes[0], bytes[1], bytes[2], bytes[3]));
    }

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

在这种情况下,您选择的项目将是一个字符串.对于您的场景,第一种方法可能更容易,但对于更复杂的场景,这将更好,请注意,在这种情况下,您可以轻松地将ComboBox绑定到带颜色的字符串集合.

点赞