我试图将列表绑定到ListBox,但完全没有任何反应。我没有得到任何错误,但我确定ListBox绑定到列表已填充,因为我有一个文本控件,显示信息显示集合中有三个项目。从后面的代码绑定列表到列表框
所以,问题是什么是需要绑定到一个列表框
<ListBox x:Name="lbSlaves" Width="300" Grid.Row="1" ItemsSource="{Binding Slaves}" >
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Width="150" Height="30" Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding MachineName}"></TextBox> <!-- Ive also tried Path=MachineName -->
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
代码背后
public List<ZTClient> Slaves { get; set; }
private void SetUpSlaves()
{
var client1 = new ZTClient()
{
MachineName = "Machine One",
IpAdress = "34534512",
Status = "Ready"
};
var client2 = new ZTClient()
{
MachineName = "Machine Two",
IpAdress = "123456",
Status = "Ready"
};
var client3 = new ZTClient()
{
MachineName = "Machine Three",
IpAdress = "65464234",
Status = "Ready"
};
AddClient(client1);
AddClient(client2);
AddClient(client3);
//Ive also tried the following
//lbSlaves.DataContext = Slaves;
tbInfoBox.Text += "Nr of slaves = " + Slaves.Count() + Slaves[0].MachineName;
}
void SetInfoTex(string newText)
{
tbInfoBox.Text = newText;
}
private void AddClient(ZTClient newClient)
{
Slaves.Add(newClient);
}
检查输出窗口是否有绑定错误。 –
使用ObservableCellection绑定列表,如果你稍后改变它们 –