如何将表/网格添加到vb.net/C# WPF窗口?

时间:2013-03-10 14:55:48

标签: c# wpf vb.net

我有一个异步服务器侦听本地网络上的客户端。当每个客户端向服务器发送连接消息时,我希望服务器在表中显示客户端的名称。

假设我已将客户端的名称和IP地址作为字符串ClientDetails分隔为_例如“PC5_192.168.1.10”

* 编辑*

我想要什么

当客户加入时,我想将每个客户端添加为表/网格的新行。

我正在使用WPF。无论是vb.net还是C#答案都可以,我可以自己翻译。

1 个答案:

答案 0 :(得分:2)

我准备了一个“WPF方式”的小例子来做到这一点。 在我的电脑中看起来像这样:

enter image description here

我使用随机值作为数据源:

 public class RandomConnectionAdder
    {
        public Timer timer;
        public Random random = new Random();

        public Action<Connection> OnConnectionAdded { get; set; }

        public RandomConnectionAdder(Action<Connection> onConnectionAdded)
        {
            OnConnectionAdded = onConnectionAdded;
            timer = new Timer(x => AddConnection(), null, 5000, 2000);
        }

        private void AddConnection()
        {
            var computernumber = random.Next(1, 50);
            var newrandomconnection = new Connection()
                {
                    ComputerName = "PC" + computernumber.ToString(), 
                    IPAddress = "192.168.1." + computernumber,
                    ConnectionTime = DateTime.Now
                };

            if (OnConnectionAdded != null)
                OnConnectionAdded(newrandomconnection);
        }
    }

请注意,我通过使用Action<Connection>委托添加了一个间接级别来保持关注点的分离。 “监听器”负责监听传入连接,添加新连接时的操作超出了其范围。

这是Model类:

  public class Connection: INotifyPropertyChanged
    {
        private string _computerName;
        public string ComputerName
        {
            get { return _computerName; }
            set
            {
                _computerName = value;
                OnPropertyChanged("ComputerName");
            }
        }

        private string _ipAddress;
        public string IPAddress
        {
            get { return _ipAddress; }
            set
            {
                _ipAddress = value;
                OnPropertyChanged("IPAddress");
            }
        }

        private DateTime _connectionTime;
        public DateTime ConnectionTime
        {
            get { return _connectionTime; }
            set
            {
                _connectionTime = value;
                OnPropertyChanged("ConnectionTime");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

这是Window Code-behind:

 public partial class Window6 : Window
    {
        private RandomConnectionAdder adder;
        private ObservableCollection<Connection> Connections;

        public Window6()
        {
            InitializeComponent();
            Connections = new ObservableCollection<Connection>();
            adder = new RandomConnectionAdder(x => Dispatcher.BeginInvoke((Action) (() => AddConnection(x))));
            DataContext = Connections;
        }

        private void AddConnection(Connection connection)
        {
            Connections.Add(connection);
        }
    }

如您所见,窗口实例化RandomConnectionAdder并将其OnConnectionAdded操作设置为lambda,该lambda通过{将ObservableCollection项添加到UI线程。 {1}}。

最后,这是整个XAML:

Dispatcher

正如您所看到的,我绝不会在代码中操纵UI元素。这使代码保持干净,简单和分离,因为应用程序逻辑/数据决不依赖于UI元素的状态。

此外,在这个例子中可以看到“将几个不同的视图绑定到同一个ViewModel”的概念,在本例中是<Window x:Class="WpfApplication5.Window6" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window6" Height="300" Width="300"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition/> <ColumnDefinition/> </Grid.ColumnDefinitions> <GroupBox Header="DataGrid"> <DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False" IsReadOnly="True"> <DataGrid.Columns> <DataGridTextColumn Header="Computer Name" Binding="{Binding ComputerName}"/> <DataGridTextColumn Header="IP Address" Binding="{Binding IPAddress}"/> <DataGridTextColumn Header="Connection Time" Binding="{Binding ConnectionTime, StringFormat='HH:mm:ss'}"/> </DataGrid.Columns> </DataGrid> </GroupBox> <GroupBox Header="Large Icons (ListBox)" Grid.Column="1"> <ListBox ItemsSource="{Binding}"> <ListBox.Template> <ControlTemplate> <ItemsPresenter/> </ControlTemplate> </ListBox.Template> <ListBox.ItemTemplate> <DataTemplate> <DockPanel Margin="5" Width="120"> <StackPanel DockPanel.Dock="Bottom"> <TextBlock Text="{Binding ComputerName}" TextAlignment="Center"/> <TextBlock Text="{Binding IPAddress}" TextAlignment="Center"/> <TextBlock Text="{Binding ConnectionTime, StringFormat='HH:mm:ss'}" TextAlignment="Center"/> </StackPanel> <Border Height="60" Width="60" BorderBrush="Black" BorderThickness="1"> <TextBlock Text="Some Icon" VerticalAlignment="Center" TextAlignment="Center"/> </Border> </DockPanel> </DataTemplate> </ListBox.ItemTemplate> <ListBox.ItemsPanel> <ItemsPanelTemplate> <WrapPanel IsItemsHost="True"/> </ItemsPanelTemplate> </ListBox.ItemsPanel> </ListBox> </GroupBox> <GroupBox Header="Tiles (ListBox)" Grid.Column="2"> <ListBox ItemsSource="{Binding}"> <ListBox.Template> <ControlTemplate> <ItemsPresenter/> </ControlTemplate> </ListBox.Template> <ListBox.ItemTemplate> <DataTemplate> <DockPanel Margin="5" Width="120"> <Border Height="40" Width="50" BorderBrush="Black" BorderThickness="1" DockPanel.Dock="Left"> <TextBlock Text="Some Icon" VerticalAlignment="Center" TextAlignment="Center"/> </Border> <StackPanel> <TextBlock Text="{Binding ComputerName}" TextAlignment="Center"/> <TextBlock Text="{Binding IPAddress}" TextAlignment="Center"/> <TextBlock Text="{Binding ConnectionTime, StringFormat='HH:mm:ss'}" TextAlignment="Center"/> </StackPanel> </DockPanel> </DataTemplate> </ListBox.ItemTemplate> <ListBox.ItemsPanel> <ItemsPanelTemplate> <WrapPanel IsItemsHost="True"/> </ItemsPanelTemplate> </ListBox.ItemsPanel> </ListBox> </GroupBox> </Grid> </Window> 本身。

这是所有事情的“WPF”方法。您几乎从不必在代码中操作UI元素,至少在应用程序逻辑或数据方面是这样。

只需将我的代码复制并粘贴到ObservableCollection中,然后自行查看结果。