![](/img/trans.png)
[英]WPF datagrid binding error on datagridtextcolumn.ElementStyle
[英]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.