C# WPF:无法将项添加到组合框
本文关键字:添加 组合 WPF | 更新日期: 2023-09-27 18:30:32
我有一个组合框,我尝试在其中添加当前进程(其窗口标题)。我的代码是:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
List<ComboBoxItem> list = new List<ComboBoxItem>();
ComboBoxItem item;
Process[] _processes = Process.GetProcesses();
foreach (Process process in _processes)
{
item = new ComboBoxItem();
item.Content = process.MainWindowTitle;
item.ToolTip = process.MainWindowTitle;
list.Add(item)
}
cbProcesses.ItemsSource = list;
}
和 XAML:
<ComboBox x:Name="cbProcesses" HorizontalAlignment="Left" Margin="101,40,0,0" VerticalAlignment="Top" Width="120" SelectionChanged="comboProcesses_Selected" IsSynchronizedWithCurrentItem="True" SelectedIndex="0">
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem" BasedOn="{StaticResource {x:Type ComboBoxItem}}">
<EventSetter Event="MouseEnter" Handler="cbProcesses_MouseEnter" />
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
尝试cbProcesses.ItemsSource = list
时崩溃。我能做什么?
这对我来说是完美的:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ComboBox x:Name="cbProcesses" HorizontalAlignment="Left" Margin="101,40,0,0" VerticalAlignment="Top" Width="120" IsSynchronizedWithCurrentItem="True" SelectedIndex="0">
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem" BasedOn="{StaticResource {x:Type ComboBoxItem}}">
<EventSetter Event="MouseEnter" Handler="cbProcesses_MouseEnter" />
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
</Grid>
</Window>
C#:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication1
{
/// <summary>
/// Interaktionslogik für MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Loaded += MainWindow_Loaded;
}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
List<ComboBoxItem> list = new List<ComboBoxItem>();
ComboBoxItem item;
Process[] _processes = Process.GetProcesses();
foreach (Process process in _processes)
{
if (!String.IsNullOrEmpty(process.MainWindowTitle))
{
item = new ComboBoxItem();
item.Content = process.MainWindowTitle;
item.ToolTip = process.MainWindowTitle;
list.Add(item);
}
}
cbProcesses.ItemsSource = list;
}
private void cbProcesses_MouseEnter(object sender, MouseEventArgs e)
{
}
}
}
我只是补充说:if (!String.IsNullOrEmpty(process.MainWindowTitle))