【问题标题】:Select ComboBoxItem Using String使用字符串选择 ComboBoxItem
【发布时间】:2018-01-31 09:40:04
【问题描述】:

我有一个使用带有背景颜色的 ComboBoxItems 而不是 <System:String> 的组合框。

<ComboBox x:Name="cboColors"
            HorizontalAlignment="Right"
            Margin="0,135,212,0" 
            VerticalAlignment="Top"
            Width="103">
    <ComboBoxItem Background="White" Foreground="Black" Content="White"/>
    <ComboBoxItem Background="Gray" Foreground="White" Content="Gray"/>
    <ComboBoxItem Background="#FF262626" Foreground="White" Content="Dark Gray"/>
    <ComboBoxItem Background="Black" Foreground="White" Content="Black"/>
    <ComboBoxItem Background="#FFfdfd02" Content="Yellow"/>
    <ComboBoxItem Background="#FF9aafe4" Content="Blue"/>
    <ComboBoxItem Background="#FFffb0b0" Content="Pink"/>
</ComboBox>

我可以像这样得到ComboBoxItem的值

ComboBoxItem selectedItem = (ComboBoxItem)(mainwindow.cboColors.SelectedValue);
string selected = (string)(selectedItem.Content);

如何使用字符串"Yellow"设置 ComboBox SelectedItem?

cboColors.SelectedItem = "Yellow";

组合框不会改变。

【问题讨论】:

  • 您需要使用字符串来识别ItemSource(组合框项)中的哪个对象成为选中项。即 cboColors.SelectedItem = cboColors.Items.FirstOrDefault(item => item.Content.Equals("Yellow"));
  • @CodexNZ 它给出错误,“ItemCollection 不包含 'FirstOrDefault' 的定义”。
  • 为什么你回到硬编码的 xaml 对象而不是一个类来表示你的组合中的项目?此处提供的答案:stackoverflow.com/questions/45703106/… 将允许您使用绑定集合作为查找的源,而无需执行您正在尝试的操作。您需要做的就是为您的 ComboItem 类添加属性以进行背景和前景绑定。

标签: c# wpf visual-studio combobox


【解决方案1】:

this为起点:

private void SetSelectedComboBoxItem(string itemName)
{
   ComboItem selected = MyComboItems.FirstOrDefault(i => i.Name.Equals(itemName));
  if (selected != null)
  {
    combo.SelectedItem = selected;
  }
  else
  {
    combo.SelectedItem = combo.Items[0];
  }
}

private void SetSelectedComboBoxItem(string itemName)
{
   ComboItem selected = MyComboItems.FirstOrDefault(i => i.Name.Equals(itemName));
  if (selected != null)
  {
    SelectedItem = selected;
  }
  else
  {
    SelectedItem = combo.Items[0];
  }
}

然后修改您的 ComboItem 类以包含您用于着色的属性:

public class ComboItem
{
  public string Color { get; private set; }

  public SolidColorBrush BackgroundColor { get; private set; }

  public SolidColorBrush ForegroundColor { get; private set; }

  public ComboItem(string color,  SolidColorBrush background, SolidColorBrush foreground)
  {
    Color = color;
    BackgroundColor = background;
    ForegroundColor = foreground;
  }
}

并更改您的列表初始化以包含新属性:

List<ComboItem> _myComboItems= new List<ComboItem>()
  {
    new ComboItem("White", Brushes.White, Brushes.Black),
    new ComboItem("Gray", Brushes.Gray, Brushes.White),
    new ComboItem("Dark Gray", Brushes.DarkGray, Brushes.White),
    new ComboItem("Black", Brushes.Black, Brushes.White),
    new ComboItem("Yellow", Brushes.Yellow, Brushes.Black),
    new ComboItem("Blue", Brushes.Blue, Brushes.Black),
    new ComboItem("Pink", Brushes.Pink, Brushes.Black)
  };

并修改您的 xaml 以将样式应用于 ComboBox,如下所示(这将应用于应用程序中的所有组合框控件):

<Window.Resources>
<Style TargetType="{x:Type ComboBoxItem}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type ComboBoxItem}">
        <Border Name="Border"
                Height="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ComboBox}}, Path=ActualHeight}"
                Background="{Binding BackgroundColor}"
                BorderBrush="Transparent">
          <Grid>
            <TextBlock x:Name="ItemText" 
                       TextAlignment="Left" 
                       VerticalAlignment="Center"
                       Text="{Binding Color}" 
                       Margin="5,0,0,0"
                       Foreground="{Binding ForegroundColor}"/>
          </Grid>
        </Border>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

希望我没有错过任何东西。

【讨论】:

  • 正在应用颜色。我遇到了2个问题。单击一个项目不会选择它,该框保持为空。并使用SetSelectedComboBoxItem("Yellow") 我得到一个 NullReferenceException。这是我的完整示例代码:XAML pastebin.com/raw/dwxn60VW。 C#pastebin.com/raw/494VMfQe.
  • 在您的 xaml 中,您同时使用 SelectedItem 和 SelectedIndex,只使用一个,因为它们会相互影响,即使您选择了一个项目,SelectedIndex 值也被硬编码为 0。
  • NullReferenceException 发生在哪里?使用您的调试器找出什么是 null 并修复它或防止它发生。
【解决方案2】:

您应该将SelectedItem 设置为ComboBoxItem,而不是string。您可以使用一些 LINQ 选择适当的 ComboBoxItem:

cboColors.SelectedItem = cboColors.Items.OfType<ComboBoxItem>().FirstOrDefault(x => x.Content.ToString() == "Yellow");

所选项目的类型和ComboBox中的项目必须匹配。

【讨论】:

    猜你喜欢
    • 2011-11-07
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-01
    相关资源
    最近更新 更多