无法通过 XAML 中的数据上下文访问结构变量
本文关键字:上下文 数据 访问 结构 变量 XAML | 更新日期: 2023-09-27 18:30:58
我试图创建一个应用程序,该应用程序可以打印出特定的进程以及有关它们的一些信息。我以前通过访问 system.processes 并将进程存储到数组中并将其输入 DataContext 来工作(这个。数据上下文 = 数组)。我尝试切换到使用 WMI 访问命令行参数,现在进程进入我的 ListView,但有关每个进程的信息没有显示。
我的代码:
我在 C# 中查找进程并存储其信息的函数:
public struct Processes
{
public string processID;
public string commandLine;
public string name;
}
public void FindTestProcesses()
{
List<Processes> processList = new List<Processes>();
Processes currentProcess = new Processes();
ManagementClass mgmtClass = new ManagementClass("Win32_Process");
foreach (ManagementObject process in mgmtClass.GetInstances())
{
// Basics - process name & pid
string processName = process["Name"].ToString().ToLower();
if (Regex.IsMatch(processName, @"(jtest)|(java)|(testrunner)"))
{
currentProcess.name = processName;
System.UInt32 pid = (System.UInt32)process["ProcessId"];
currentProcess.processID = pid.ToString();
// Get the command line - can be null if we don't have permissions
string cmdLine = null;
if (process["CommandLine"] != null)
{
cmdLine = process["CommandLine"].ToString();
currentProcess.commandLine = cmdLine;
}
Debug.WriteLine("{0,6} - {1} - {2}", pid, processName, cmdLine);
processList.Add(currentProcess);
}
}
foreach (Processes process in processList)
{
ListViewItem item = new ListViewItem();
}
this.DataContext = processList.ToArray();
}
还有我的 XAML:
<Window x:Class="UnitTestViewer.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Unit Test Viewer" Height="350" Width="700">
<Grid Background="Gray">
<ListView ItemsSource="{Binding}" Margin="0,0,0,29">
<ListView.View>
<GridView>
<GridViewColumn Header="name" DisplayMemberBinding="{Binding name}"/>
<GridViewColumn Header="processID" DisplayMemberBinding="{Binding processID}"/>
<GridViewColumn Header="commandLine" DisplayMemberBinding="{Binding commandLine}"/>
</GridView>
</ListView.View>
</ListView>
<Canvas>
<Button Name="refreshButton" BorderThickness="1" BorderBrush="Black" Click="RefreshProcesses" ClickMode="Release" Canvas.Right="6" Canvas.Bottom="4">Refresh</Button>
</Canvas>
</Grid>
我不明白为什么 DisplayMemberBinding 不再显示。
XAML 数据绑定旨在使用属性,我不确定它是否支持字段。
尝试更改类声明Processes
以使用属性:
public struct Processes
{
public string processID {get; set;}
public string commandLine {get; set;}
public string name {get; set;}
}
绑定是指属性而不是索引器...所以{binding name}
会寻找process.name
而不是process["name"]