【问题标题】:WPF Combobox issuesWPF 组合框问题
【发布时间】:2017-01-25 01:26:53
【问题描述】:

只是给大家一个简单的问题。

我有两个组合框,其中一个具有硬编码的数据:

<ComboBox>
    <ComboBoxItem/>
</ComboBox>

当我尝试在 SelectionChanged 上使用 case 语句时,我会从 Convert.ToString(cboForm.SelectedValue): "System.Windows.Controls.ComboBoxItem: Directional Bore" 获得值。

现在在同一个表单上,我有另一个组合框,其中包含我用comboboc.items.add() 填充的数据,并且在 SelectionChanged 之后该组合框的值是实际的文本值。

我可以做些什么来使所选值中没有"System.Windows.Controls.ComboBoxItem: "?

案例陈述:

string caseSwitch = cboForm.SelectedValue.ToString();
switch (caseSwitch)
{
    case "System.Windows.Controls.ComboBoxItem: Directional Bore":
    {
        ReportClass.DirBoreReport("","","");
        cboForm.SelectedIndex = -1;
        //MainAccess.Mw.SpecificForm = false;
        //MainAccess.Mw.frmPage.Height = 4400;
        //MainAccess.Mw.HoldPage = new Uri("DirectionalBore_Combined.xaml", UriKind.Relative);
        //if (NavigationService != null) NavigationService.Source = MainAccess.Mw.HoldPage;
        //MainAccess.Mw.SectionBar_DirectionalBore.Visibility = Visibility.Visible;
        //MainAccess.Mw.scroll.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
        //MainAccess.Mw.lblForm.Content = "DIRECTIONAL BORE";
        //MainAccess.Mw.Sbar = MainAccess.Mw.SectionBar_DirectionalBore;
        break;
    }
}

Xaml:

<ComboBox x:Name="cboForm" TabIndex="3" HorizontalAlignment="Left" Margin="746,618,0,0" VerticalAlignment="Top" Width="630" FontSize="48" FontWeight="Bold" Height="74" SelectionChanged="cboForm_SelectionChanged" >
    <ComboBoxItem Content="Directional Bore" HorizontalAlignment="Left"  />
    <ComboBoxItem Content="Drain Tile Break" HorizontalAlignment="Left"/>
    <ComboBoxItem Content="Fiber Installation" HorizontalAlignment="Left"/>
</ComboBox>

谢谢!

【问题讨论】:

  • 你应该覆盖你的对象 ToString()。
  • @Sonhja 试过了,不走运,同样的事情一直在发生。
  • 你能完整显示一下switch case statement
  • 你能发布完整的代码吗?
  • 在 XAML 上使用 DisplayMemberPath 并指定要显示的成员。

标签: c# wpf combobox


【解决方案1】:

首先将SelectedItem 转换为ComboBoxItem,然后ComboBoxItem.Content 将具有字符串值。

        ComboBoxItem item = this.cboForm.SelectedItem as ComboBoxItem;
        if (item != null)
        {
            MessageBox.Show(item.Content.ToString());
        }

【讨论】:

  • 只是一个简单的问题,当组合框是从另一个来源填充时,为什么不用转换它就可以工作?
  • 当您使用ComboBoxItem 时,ComboBoxs ItemSource 实际上是一个 List,但是当您从后面的代码中填充时,您将 List 分配给 ItemsSource,因此转换是在第二种情况下不需要。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多