所以我试图在我的列表视图中添加一行信息,但是当我这样做时,显示它很奇怪。像这样:
我正在为每个循环使用a:
foreach (Client c in clients)
{
ListViewItem i = new ListViewItem();
i.Content = new String[] { c.info.cid.ToString(), c.info.pc.ToString(),c.info.ip.ToString(), c.info.status.ToString() };
list.Items.Add(i);
}
我的客户端类使用结构来存储信息
public struct Info
{
public int cid;
public string pc;
public string ip;
public string status;
}
我也在为它添加值:
info = new Info();
info.ip = "192.168.1.100";
info.pc = "Duncan";
info.status = "idle";
info.cid = 1;
为什么它显得怪异?有人可以帮忙吗?
我的ListView XAML:
<ListView Height="247" HorizontalAlignment="Left" Margin="4,6,0,0" Name="list" VerticalAlignment="Top" Width="319" Background="#FF454545" ItemsSource="{Binding}" SelectionMode="Multiple" Grid.Column="0">
<ListView.View>
<GridView AllowsColumnReorder="False">
<GridViewColumn Header="ID" Width="30" />
<GridViewColumn Header="Computer" Width="100" />
<GridViewColumn Header="IP" Width="100" />
<GridViewColumn Header="Status" Width="100" />
</GridView>
</ListView.View>
</ListView>
答案 0 :(得分:2)
此代码中存在一些错误的内容。如果要使用绑定在ListView中推送数据,则必须具有要绑定的属性的有效ViewModel。您必须在GridViewColumns上定义绑定。
此外,WPF不知道如何绑定字段,因此您需要为要显示的每个数据使用.NET属性。这是一个非常原始的例子,它不是一个现实的场景,但应该可以帮助你开始:
<强> Window.xaml 强>
<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">
<ListView Height="247" HorizontalAlignment="Left" Margin="4,6,0,0" Name="list" VerticalAlignment="Top" Width="319" Background="#FF454545" ItemsSource="{Binding Clients}" SelectionMode="Multiple" Grid.Column="0">
<ListView.View>
<GridView AllowsColumnReorder="False">
<GridViewColumn Header="ID" Width="30" DisplayMemberBinding="{Binding Id}" />
<GridViewColumn Header="Computer" Width="100" DisplayMemberBinding="{Binding Computer}" />
<GridViewColumn Header="IP" Width="100" DisplayMemberBinding="{Binding Ip}" />
<GridViewColumn Header="Status" Width="100" DisplayMemberBinding="{Binding Status}" />
</GridView>
</ListView.View>
</ListView>
</Window>
<强> MainWindow.xaml.cs 强>
/// <summary>
/// Logique d'interaction pour MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
public IEnumerable<DummyClient> Clients
{
get
{
for (int i = 0; i < 10; i++)
{
var info = new Info();
info.ip = "192.168.1.100";
info.pc = "Duncan";
info.status = "idle";
info.cid = 1;
yield return new DummyClient(info);
}
}
}
}
public class DummyClient
{
public DummyClient(Info info)
{
Info = info;
}
public string Ip { get { return Info.ip; } }
public string Computer { get { return Info.pc; } }
public string Status { get { return Info.status; } }
public int Id { get { return Info.cid; } }
public Info Info
{
get;
private set;
}
}
public struct Info
{
public int cid;
public string pc;
public string ip;
public string status;
}
再一次,它不是应该做的方式,但这是一个开始。例如,如果你想要两种方式绑定工作,DummyClient应该实现INotifyPropertyChanged。