在ComboBox中获取所选项目

时间:2017-02-21 20:42:28

标签: c# combobox uwp

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

<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>

我需要从矩形填充中获取一个画笔(或者至少是字符串填充值)。所以我尝试了这个:

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

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

那我怎么能得到它?我需要它从ComboBox的选定值中着色。谢谢!

1 个答案:

答案 0 :(得分:2)

我不确定为什么你在comboboxitem的内容中得到 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>

然后您只需将所选项目转换为矩形

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 绑定到带颜色的字符串集合。