【问题标题】:WPF datagrid Binding error?WPF数据网格绑定错误?
【发布时间】:2014-04-15 12:30:46
【问题描述】:

我正在开发基于网络的应用程序,该应用程序使用 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>

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

【问题讨论】:

  • dg.ItemsSource = ipmac; 怎么样?

标签: c# wpf datagrid


【解决方案1】:

DataGrid 中显示IPMAC 列表的最简单方法是在填充列表后从代码中设置ItemsSource

dg.ItemsSource = ipmac;

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

  • 正确设置DataContext。因为数据绑定从当前数据上下文解析绑定路径。
  • ipmac 声明为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" ... />

【讨论】:

  • 它解决了我现在感觉很好的问题,但另一件事是它在第一行显示 mac 地址,在第二行显示 ip 会是什么问题?
  • 这很奇怪。没有更多信息就不知道了。您确定不是填充了错误数据的集合吗?
猜你喜欢
  • 2019-03-08
  • 2011-09-28
  • 2010-11-15
  • 1970-01-01
  • 1970-01-01
  • 2011-08-15
  • 2012-07-03
相关资源
最近更新 更多