[英]Listbox Not binding to a BindingList<T>
我有綁定到窗體上的列表框BindingList<T>
在后面的代碼,但內未顯示的項目BindingList<T>
XAML:
<Window x:Class="MessageServer.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MessageServer"
Name="mainWindow" Title="Message Exchange Server"
Height="350" Width="525" Closing="Window_Closing">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<ListBox Name="OutputList" Grid.Row="0" />
<ListBox Name="Connected" Grid.Row="1" ItemsSource="{Binding ElementName=mainWindow, Path=ConnectedClients}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=FullIPAddress}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Grid>
代碼背后:
private BindingList<Client> _ConnectedClients;
public BindingList<Client> ConnectedClients
{
get { return _ConnectedClients; }
set { _ConnectedClients = value; }
}
public class Client : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private TcpClient _tcpClient;
public TcpClient tcpClient
{
get { return _tcpClient; }
set
{
_tcpClient = value;
NotifyPropertyChanged();
}
}
public string FullIPAddress
{
get { return _tcpClient.Client.RemoteEndPoint.ToString(); }
}
public string IPAddress
{
get { return _tcpClient.Client.RemoteEndPoint.ToString().Split(':').ElementAt(0); }
}
public string PortNumber
{
get { return _tcpClient.Client.RemoteEndPoint.ToString().Split(':').ElementAt(1); }
}
public Client(TcpClient tcpClient)
{
this.tcpClient = tcpClient;
NotifyPropertyChanged();
}
private void NotifyPropertyChanged()
{
NotifyPropertyChanged("tcpClient");
NotifyPropertyChanged("FullIPAddress");
NotifyPropertyChanged("IPAddress");
NotifyPropertyChanged("PortNumber");
}
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
任何想法,為什么列表框不顯示項目? 不確定是否值得一提,但是將項目添加到BindingList時,這是在UI線程的單獨線程上完成的。 但是我嘗試使用Dispatcher.BeginInvoke()但仍然無法正常工作...
聽起來您確實想使用ObservableCollection。 聽起來BindingList應該起作用,但是在此SO帖子上,他們似乎說ObservableCollection用於WPF,而BindingList用於Winforms: BindingList和ObservableCollection之間的區別
嘗試使用ObservableCollection<T>
。 它是專門為WPF設計的。
您正在嘗試綁定到Window.ConnectedClients
,這是一個不存在的屬性。
您需要更改對DataContext.ConnectedClients
的綁定才能綁定到Window.DataContext.ConnectedClients
ItemsSource="{Binding ElementName=mainWindow, Path=DataContext.ConnectedClients}"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.