[英]Bind a list to a ListBox from code behind
我試圖將列表綁定到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);
}
您綁定默認情況下綁定TwoWay
的屬性( TextBox.Text
)。 您的MachineName
是否有公共設置器? 如果未設置,則將綁定模式更改為OneWay
或者使設置器更易於訪問以防止綁定錯誤。
您還可以手動更新信息文本,但是更改通知不支持ListBox
綁定,因此它們可能不會同步。 您應該綁定到ObservableCollection<ZTClient>
,如果您想自己更改實例,則ZTClient
類應實現INotifyPropertyChanged
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.