我有一個窗體上的ListBox綁定到代碼後面的BindingList<T>
,但不顯示BindingList<T>
中的項目。列表框不綁定到綁定列表<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:http://stackoverflow.com/questions/4284663/difference-between-observablecollection-and-bindinglist –
ShelbyZ
我改變了BindingList的類型ObservableCollection,這工作沒有問題,唯一的變化,我不得不做的是,當添加/從列表中刪除項目,我必須做到這一點很容易實現的UI線程(對於那些誰知道)使用... Dispatcher.BeginInvoke(新的行動(()=> ConnectedClients.Add(客戶端))); –