繁体   English   中英

WPF datagrid绑定错误?

[英]WPF datagrid Binding error?

我正在基于网络的应用程序上工作,该应用程序使用C#连接到网络设备,前端在WPF上。问题是我想在运行特定命令后提取数据,提取后希望它显示在DataGrid上。根据需要使用正则表达式正确提取,但我想在Datagrid上显示的部分没有显示,但是在控制台上正确显示了。代码是:

public class IPMAC
{
    public string ip { get; set; }
    public string mac { get; set; }
}

List<IPMAC> ipmac = new List<IPMAC>();
string pattern = @"(F8-F7-D3-00\S+)";
MatchCollection matches = Regex.Matches(stringData, pattern);

foreach (Match match in matches)
{
    Console.WriteLine("Hardware Address : {0}", match.Groups[1].Value);
    ipmac.Add(new IPMAC(){mac=match.Groups[1].Value});
}
string pattern2 = @"(192.168.1\S+)";
MatchCollection matchesIP = Regex.Matches(stringData, pattern2);

foreach (Match match in matchesIP)
{
    Console.WriteLine("IP Address : {0}", match.Groups[1].Value);
    ipmac.Add(new IPMAC() { ip = match.Groups[1].Value });

XAML是:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="250"/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <DataGrid Name="dg" Grid.Row="0" Height="250" AutoGenerateColumns="False" >     
        <DataGrid.Columns>
            <DataGridTextColumn Header="Mac Addresses" Binding="{Binding Path=mac}"/>
            <DataGridTextColumn Header="IP Addresses" Binding="{Binding Path=ip}"/>
        </DataGrid.Columns>
    </DataGrid>

简而言之,我不明白如何在数据网格上显示输出,因为它在控制台上显示。请帮助?

DataGrid显示IPMAC列表的最简单方法是,在填充列表之后,通过代码设置ItemsSource

dg.ItemsSource = ipmac;

或者您可以按照以下步骤使用DataBinding

  • 正确设置DataContext 因为数据绑定从当前数据上下文解析绑定路径。
  • ipmac声明为ObservableCollection类型的公共属性 ObservableCollection具有内置的机制, ObservableCollection在添加或从集合中删除项目时通知UI刷新。 并且数据绑定不适用于成员/字段。
  • ItemsSource绑定到ipmac属性

展示以上步骤的代码段:

//declare ipmac as public property
public ObservableCollection<IPMAC> ipmac { get; set; } 

//In constructor : initialize ipmac and set up DataContext
ipmac = new ObservableCollection<IPMAC>();
this.DataContext = this;

//In XAML : bind ItemsSource to ipmac
<DataGrid ItemSource="{Binding ipmac}" Name="dg" ... />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM