我试图将列表绑定到ListBox但绝对没有任何反应。我没有得到任何错误,但我确定ListBox绑定到的列表已填充因为我有一个Text控件,显示信息显示集合中有三个项目。
所以问题是绑定到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);
}
答案 0 :(得分:0)
默认绑定绑定TextBox.Text
的属性(TwoWay
)。你的MachineName
有公共制定者吗?如果没有将绑定模式更改为OneWay
,或者更确切地说使setter更易于访问以防止绑定错误。
您也可以手动更新信息文本,但更改通知不支持ListBox
绑定,因此它们可能无法同步。您应该绑定到ObservableCollection<ZTClient>
,如果您想自己更改实例,那么ZTClient
类应该实现INotifyPropertyChanged
。