我在组合框中尝试添加当前进程(其窗口标题)。我的代码是:
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
时崩溃了。我该怎么办?
答案 0 :(得分:0)
这对我来说很完美:
<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))