WPF C# - 向DataGrid添加3个字符串

时间:2016-05-29 19:50:05

标签: c# wpf datagrid

我正在为基于Source Engine的游戏制作一个启动器(想象一下像LoL启动器这样的东西)。

我有一个可以查询服务器数据的SSQLib(服务器名称,当前播放器/ Maxplayers,地图名称)。我想在DataGrid中列出这三个数据。那么,我如何在DataGrid中列出这些?

这是我的代码:

private void btnLoadDataGrid_Click(object sender, RoutedEventArgs e)
        {
            string ip = "192.168.1.73";
            int port = 27015;

            IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse(ip), port);

            SSQL query = new SSQL();
            ServerInfo serverInformation = query.Server(endpoint);

            string servername = serverInformation.Name.ToString();
            string mapname = serverInformation.Map.ToString();
            string servermaxplayer = serverInformation.MaxPlayers.ToString();
        }

1 个答案:

答案 0 :(得分:0)

当您使用MVVMC并且我正确理解您尝试执行的操作时,您的代码应类似于以下内容:

查看:

<DataGrid x:Name="MyDataGrid"   ItemsSource="{Binding Path=MyObservableCollection}" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="ServerName" Binding="{Binding servername}"/>
                <DataGridTextColumn Header="MapName" Binding="{Binding mapname}"/>
                <DataGridTextColumn Header="MaxPlayers" Binding="{Binding servermaxplayer}"/>               
            </DataGrid.Columns>
</DataGrid>

视图模型:

private ObservableCollection<ServerModel> _myObservableCollection;

        public ObservableCollection<ServerModel> MyObservableCollection
        {
            get { return _myObservableCollection; }
            set
            {
                if (_myObservableCollection == value)                                
                    return;
                _myObservableCollection = value;                                     
                OnPropertyChanged("MyObservableCollection");                         
            }
        }

控制器:

private LauncherViewModel mViewModel;             

        public void Initialize()                                          
        {
            var view = new Launcher();

            mViewModel = new LauncherViewModel
            {
                MyObservableCollection = new ObservableCollection<ServerModel>(),
            };
            view.DataContext = mViewModel;
            view.ShowDialog();

        }

型号:

public class ServerModel

public string servername { get; set; }
public string mapname { get; set; }
public int servermaxplayer { get; set; }

此外,您应该将servermaxplayer属性定义为int,因为它是一个数字,而不是字符串 - &gt;见模型。 :)