【问题标题】:WPF - add static items to a combo boxWPF - 将静态项目添加到组合框
【发布时间】:2009-11-24 17:53:27
【问题描述】:

我已经说过了,我再说一遍,WPF 最简单的例子在网上也最难找到:)

我有一个需要显示的组合框,但它不需要数据绑定或其他任何内容,内容是静态的。如何使用 XAML 将静态项目列表添加到组合框中?

【问题讨论】:

    标签: wpf xaml combobox


    【解决方案1】:

    这是来自 MSDN 的代码和链接 - Article Link,您应该查看它以了解更多详细信息。

    <ComboBox Text="Is not open">
        <ComboBoxItem Name="cbi1">Item1</ComboBoxItem>
        <ComboBoxItem Name="cbi2">Item2</ComboBoxItem>
        <ComboBoxItem Name="cbi3">Item3</ComboBoxItem>
    </ComboBox>
    

    【讨论】:

      【解决方案2】:

      像这样:

      <ComboBox Text="MyCombo">
      <ComboBoxItem  Name="cbi1">Item1</ComboBoxItem>
      <ComboBoxItem  Name="cbi2">Item2</ComboBoxItem>
      <ComboBoxItem  Name="cbi3">Item3</ComboBoxItem>
      </ComboBox>
      

      【讨论】:

        【解决方案3】:

        您还可以在代码中添加项目:

        cboWhatever.Items.Add("SomeItem");
        

        此外,要在您控制显示/值的位置添加一些内容(根据我的经验,几乎绝对需要)您可以这样做。我在这里找到了一个很好的 stackoverflow 参考:

        Key Value Pair Combobox in WPF

        总结代码是这样的:

        ComboBox cboSomething = new ComboBox();
        cboSomething.DisplayMemberPath = "Key";
        cboSomething.SelectedValuePath = "Value";
        cboSomething.Items.Add(new KeyValuePair<string, string>("Something", "WhyNot"));
        cboSomething.Items.Add(new KeyValuePair<string, string>("Deus", "Why"));
        cboSomething.Items.Add(new KeyValuePair<string, string>("Flirptidee", "Stuff"));
        cboSomething.Items.Add(new KeyValuePair<string, string>("Fernum", "Blictor"));
        

        【讨论】:

          【解决方案4】:
          <ComboBox Text="Something">
                      <ComboBoxItem Content="Item1"></ComboBoxItem >
                      <ComboBoxItem Content="Item2"></ComboBoxItem >
                      <ComboBoxItem Content="Item3"></ComboBoxItem >
          </ComboBox>
          

          【讨论】:

          • 请添加信息以及为什么您的解决方案可能对 OP 有所帮助
          • 我发现知道“内容”属性是表单上显示的内容很有帮助,其他答案(包括我的答案)没有说明。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-11-26
          • 1970-01-01
          • 2016-01-19
          • 2017-10-28
          • 2017-11-01
          相关资源
          最近更新 更多