コードの後ろにBindingList<T>
にバインドされたフォームにListBoxがありますが、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の場合はです:http://stackoverflow.com/questions/4284663/difference-between-observablecollection-and-bindinglist私は –
ShelbyZ
ですBindingListをObservableCollection型に変更しました。これは問題なく動作しました。リストから項目を追加/削除するときに唯一行った変更は、簡単に実現できるUIスレッドで行う必要があったということですDispatcher.BeginInvoke(新しいアクション(()=> ConnectedClients.Add(クライアント))); –