首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从Api中填充服务器列表并在WPF ListView .Net Core3.1中显示

如何从Api中填充服务器列表并在WPF ListView .Net Core3.1中显示
EN

Stack Overflow用户
提问于 2020-01-17 13:54:31
回答 1查看 189关注 0票数 0

我正在创建VPN WPF软件,我有各种APIs,让我们说一下serverlist,它的链接是

https://webservice.abcd.com/serverlist

现在,我将服务器列表的模型类作为

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Text;

namespace VirtualPN.Model
{
class ServerModel
{
    public string error { get; set; }
    public string message { get; set; }
    public Server[] servers { get; set; }
}

public class Server
{
    public string SID{ get; set; }
    public string Scountry { get; set; }
    public string Sdns { get; set; }
    public string Sport { get; set; }
    public string Spsk { get; set; }
    public string pptp { get; set; }
    public string l2tp { get; set; }
    public string tcp { get; set; }
    public string udp { get; set; }
    public string openconnect { get; set; }
    public string ikev2 { get; set; }
    public string sstp { get; set; }
    public string p2p { get; set; }
    public string videostreaming { get; set; }
    public string security { get; set; }
    public string voip { get; set; }
    public string enable { get; set; }
    public string maintmode { get; set; }
    public string iso { get; set; }
    public string free { get; set; }
    public string recent { get; set; }
    public string time { get; set; }
    public string fav { get; set; }
    public int Pingrate { get; set; }
    public string IsFavorite { get; set; }

    public string FavProtocol { get; set; }
}
}

现在,我有了多个国家服务器,并希望将其显示为ListView窗口,在该窗口中,每个服务器都可以选择连接VPN服务。我怎么能做到这一点。国家名称,城市域名系统是重要的

代码语言:javascript
复制
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Threading.Tasks;
using Microsoft.VisualBasic;
using System.Diagnostics;
using System.Collections;
using VirtualPN.Model;
namespace VirtualPN.Classes
{
class Global
{
    public static ServerModel sm = new ServerModel();
    public static Web_Service service = new Web_Service();
    static ArrayList nic_arr = new ArrayList();
    static bool IsdnsStatic = false;




    public Global()
    {


    }


    public class ServerType
    {
        public static string type
        {
            get; set;
        }
    }

    public static ServerModel getModel()
    {
        return sm;
    }

    public static Web_Service GetService()
    {
        return service;
    }

    public class _Server : Server
    {

        public string SId { get; set; }
        public string ServerCountry { get; set; }
        public string SDNS { get; set; }

        public string Siso { get; set; }
        public string SKey { get; set; }
        public string Sport { get; set; }
        public string Spptp { get; set; }
        public string Sl2tp { get; set; }
        public string Stcp { get; set; }
        public string Sudp { get; set; }
        public string SopenConnect { get; set; }
        public string Sikev2 { get; set; }
        public string Sstp { get; set; }
        public string Sp2p { get; set; }
        public string Svideostreaming { get; set; }
        public string Svoip { get; set; }
        public string Ssecurity { get; set; }
        public int Spingrate { get; set; }
        public string GroupName { get; set; }
        public string SIsFavorite { get; set; }
        public string IsFree { get; set; }
        public string IsRecent { get; set; }
        public string SIsTime { get; set; }
        public string Smaintmode { get; set; }


    }


    public ServerModel getServerModel
    {
        get; set;

    }


    public static string Account_Person_Name
    {
        get; set;

    }

    public static double RemainingDays
    {
        get; set;

    }

    public static DateTime DueDate
    {
        get; set;
    }

    public static bool IsfreeAccount
    {
        get; set;
    }

    public static string AccountType
    {
        get; set;
    }

    public static double TotalSubscriptionDays
    {
        get; set;
    }


    public class UrlItems
    {
        public int id { get; set; }
        public string url { get; set; }
    }



    public static void Window_Closing()
    {
        Process.GetCurrentProcess().Kill();
    }


    public static string UserName { get; set; }
    public static string password { get; set; }

    public static string GetActiveIp()
    {
        var data = Task.Run(() => Web_Service.GetIPData()).Result;
        var model = Web_Service.Map_IPModel(data.ToString());

        var ip = model.ip;

        return ip;
    }

    public static string GetActiveLocation()
    {
        var data = Task.Run(() => Web_Service.GetIPData()).Result;
        var model = Web_Service.Map_IPModel(data.ToString());

        var ip = model.country;

        return ip;
    }

    public static DateTime GetLiveDate()
    {

        var data = Task.Run(() => Web_Service.GetLiveDate()).Result;

        DateTime reg = DateTime.Parse(data);

        return reg.Date;
    }

    public static bool IsValidIpAddress(string paddress)
    {
        if (string.IsNullOrWhiteSpace(paddress))
            return false;

        var splitValues = paddress.Split('.');
        if (splitValues.Length != 4)
            return false;

        byte tempForParsing;

        return splitValues.All(r => byte.TryParse(r, out tempForParsing));
    }
    public static void Disable_Network()
    {
        // Interaction.Shell("cmd.exe /c" + value);
        string targetURL = "netsh advfirewall firewall add rule name = Block All Traffic dir =in action = allow port enable = yes remoteip = 5, 46, 48 - 1722, 1724 - 65535,LocalSubnet profile = public";

        var psi = new ProcessStartInfo
        {
            FileName = targetURL,
            UseShellExecute = true
        };
        Process.Start(psi);




    }


    public static void Activate_KillSwitch()
    {
        foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
        {


            if (ni.OperationalStatus == OperationalStatus.Up && (ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet || ni.NetworkInterfaceType == NetworkInterfaceType.FastEthernetFx || ni.NetworkInterfaceType == NetworkInterfaceType.FastEthernetT || ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211) && ni.NetworkInterfaceType != NetworkInterfaceType.Loopback && ni.NetworkInterfaceType != NetworkInterfaceType.Tunnel)
            {
                if (ni.GetIPProperties().GatewayAddresses.FirstOrDefault() != null)
                {
                    string targetURL = "netsh interface set interface " + ni.Name + " DISABLED";

                    var psi = new ProcessStartInfo
                    {
                        FileName = targetURL,
                        UseShellExecute = true
                    };
                    Process.Start(psi);
                    nic_arr.Add(ni.Name);
                    // Interaction.Shell("cmd.exe /c" + vpnKillString, Constants.vbHide;

                }


            }
        }
    }

    public static void EnableKillSwitch()
    {
        string targetURL = "netsh advfirewall firewall del rule name = 'BlockOutbound'";

        var psi = new ProcessStartInfo
        {
            FileName = targetURL,
            UseShellExecute = true
        };
        Process.Start(psi);
    }

    public static List<_Server> ServerListGlobal { get; set; }
    public static List<_Server> FavoriteServerListGlobal { get; set; }
    public static List<_Server> RecentServerListGlobal { get; set; }

    public static string ethernetIp
    {
        get; set;
    }

    public static DateTime CurrentDate
    {
        get; set;
    }

    public static string ethernetFXIp
    {
        get; set;
    }

    public static string ethernetTIp
    {
        get; set;
    }


    public static string wirelessIP
    {
        get; set;
    }

    public static void getAdaptersIP()
    {
        foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
        {


            if (ni.OperationalStatus == OperationalStatus.Up && (ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet || ni.NetworkInterfaceType == NetworkInterfaceType.FastEthernetFx || ni.NetworkInterfaceType == NetworkInterfaceType.FastEthernetT || ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211) && ni.NetworkInterfaceType != NetworkInterfaceType.Loopback && ni.NetworkInterfaceType != NetworkInterfaceType.Tunnel)
            {
                if (ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
                {
                    if (ni.GetIPProperties().GatewayAddresses.FirstOrDefault() != null)

                    {
                        ethernetIp = ni.GetIPProperties().UnicastAddresses[1].Address.ToString();

                    }


                }
                else if (ni.NetworkInterfaceType == NetworkInterfaceType.FastEthernetFx)
                {
                    if (ni.GetIPProperties().GatewayAddresses.FirstOrDefault() != null)

                    {
                        ethernetFXIp = ni.GetIPProperties().UnicastAddresses[1].Address.ToString();
                    }
                }

                else if (ni.NetworkInterfaceType == NetworkInterfaceType.FastEthernetT)
                {
                    if (ni.GetIPProperties().GatewayAddresses.FirstOrDefault() != null)

                    {
                        {
                            ethernetTIp = ni.GetIPProperties().UnicastAddresses[1].Address.ToString();
                        }
                    }
                }

                else if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211)
                {
                    if (ni.GetIPProperties().GatewayAddresses.FirstOrDefault() != null)

                    {
                        wirelessIP = ni.GetIPProperties().UnicastAddresses[1].Address.ToString();
                        if (ni.GetIPProperties().GetIPv4Properties().IsDhcpEnabled)
                        {
                            if (ni.GetIPProperties().DhcpServerAddresses.FirstOrDefault().ToString() != ni.GetIPProperties().DnsAddresses.FirstOrDefault().ToString())
                            {

                                dnsStatic = ni.GetIPProperties().DnsAddresses.FirstOrDefault().ToString();
                                IsdnsStatic = true;
                            }
                        }
                        else
                        {
                            dnsStatic = ni.GetIPProperties().DnsAddresses.FirstOrDefault().ToString();
                            IsdnsStatic = true;
                        }



                    }


                }

            }


        }
    }

    public static string dnsStatic
    { get; set; }

    public static string vpndnsServer
    { get; set; }

    public static void dnsLeakFix()
    {
        IsdnsStatic = false;

        foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
        {

            if (ni.OperationalStatus == OperationalStatus.Up && (ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet || ni.NetworkInterfaceType == NetworkInterfaceType.FastEthernetFx || ni.NetworkInterfaceType == NetworkInterfaceType.FastEthernetT || ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211) && ni.NetworkInterfaceType != NetworkInterfaceType.Loopback && ni.NetworkInterfaceType != NetworkInterfaceType.Tunnel)
            {
                string targetURL = "ipconfig /flushdns";

                var psi = new ProcessStartInfo
                {
                    FileName = targetURL,
                    UseShellExecute = true
                };
                Process.Start(psi);


                if (ni.GetIPProperties().GatewayAddresses.FirstOrDefault() != null)
                {
                    if (ni.GetIPProperties().GetIPv4Properties().IsDhcpEnabled)
                    {
                        if (ni.GetIPProperties().DhcpServerAddresses.FirstOrDefault().ToString() != ni.GetIPProperties().DnsAddresses.FirstOrDefault().ToString())
                        {

                            dnsStatic = ni.GetIPProperties().DnsAddresses.FirstOrDefault().ToString();
                            IsdnsStatic = true;
                        }
                    }
                    else
                    {
                        dnsStatic = ni.GetIPProperties().DnsAddresses.FirstOrDefault().ToString();
                        IsdnsStatic = true;
                    }



                    string dnsFix = "netsh interface IPv4 set dnsserver \"" + ni.Name + "\" static 8.8.8.8 both";
                    Process.Start(dnsFix);
                    //Interaction.Shell("cmd.exe /c" + dnsFix, AppWinStyle.Hide);
                }


            }


        }


        Messagebox box = new Messagebox("DNS Leak has been fixed!. Enjoy your browsing...");
        box.ShowInTaskbar = false;
        box.ShowDialog();
    }

    public static void dnsLeak_Release()
    {
        foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
        {

            if (ni.OperationalStatus == OperationalStatus.Up && (ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet || ni.NetworkInterfaceType == NetworkInterfaceType.FastEthernetFx || ni.NetworkInterfaceType == NetworkInterfaceType.FastEthernetT || ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211) && ni.NetworkInterfaceType != NetworkInterfaceType.Loopback && ni.NetworkInterfaceType != NetworkInterfaceType.Tunnel)
            {
                string targetURL = "ipconfig /flushdns";

                var psi = new ProcessStartInfo
                {
                    FileName = targetURL,
                    UseShellExecute = true
                };
                Process.Start(psi);

                if (ni.GetIPProperties().GatewayAddresses.FirstOrDefault() != null)
                {

                    if (IsdnsStatic == false)
                    {
                        string dnsFix = "netsh interface IPv4 set dnsserver \"" + ni.Name + "\" dhcp";
                        Process.Start(dnsFix);


                   ////     Interaction.Shell("cmd.exe /c" + dnsFix, AppWinStyle.Hide);
                    }
                    else if (IsdnsStatic == true)
                    {
                        string dnsFix = "netsh interface IPv4 set dnsserver \"" + ni.Name + "\" dhcp";
                        Process.Start(dnsFix);

                       //Interaction.Shell("cmd.exe /c" + dnsFix, AppWinStyle.Hide);


                    }


                   Usercredentials.Default.IsDNSLeakEnabled = false;
                   Usercredentials.Default.Save();

                }

            }
        }
        Messagebox box = new Messagebox("DNS settings has been set to default.");
        box.ShowInTaskbar = false;
        box.ShowDialog();
    }



}

}

EN

回答 1

Stack Overflow用户

发布于 2020-01-17 14:04:22

如果您使用的是MVVM:

一般的方法是保存ObservableCollection中的服务器集合,并将其绑定到ListViewItemsSource属性。

如果不使用MVVM:

您可以从ListView后面的代码设置/更新WindowItemsSource属性。

也.

您可以通过将ListViewItemTemplate属性设置为自定义DataTemplate并在那里做任何您想做的事情来定义项目的外观和显示的数据。

这里是和MVVM示例

窗口XAML代码:

代码语言:javascript
复制
<Window x:Class="ExampleApp.ServerView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="ServerView" Height="450" Width="800">
    <Grid>
        <ListView ItemsSource="{Binding Servers}" SelectedItem="{Binding SelectedServer}" SelectionMode="Single">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <Border Padding="5">
                        <StackPanel>
                            <TextBlock Text="{Binding CountryName, StringFormat='Country: {0}'}"  />
                            <TextBlock Text="{Binding CityDns, StringFormat='DNS: {0}'}" />
                        </StackPanel>
                    </Border>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
        <Button Content="Refresh" Click="BtnRefresh_Click" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="10" Padding="10"/>
    </Grid>
</Window>

代码后面的窗口代码:

代码语言:javascript
复制
using System.Windows;

namespace ExampleApp
{
    public partial class ServerView : Window
    {
        private readonly ServerViewModel _model;
        public ServerView()
        {
            InitializeComponent();
            _model = new ServerViewModel();
            DataContext = _model;
        }

        private void BtnRefresh_Click(object sender, RoutedEventArgs e)
        {
            _model.ReloadServers();
        }
    }
}

ViewModel和服务器类代码:

代码语言:javascript
复制
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace ExampleApp
{
    public class ServerViewModel : INotifyPropertyChanged
    {
        public ObservableCollection<Server> Servers { get; set; } = new ObservableCollection<Server>();

        private Server _selectedServer;
        public Server SelectedServer
        {
            get => _selectedServer;
            set
            {
                if(_selectedServer != value)
                {
                    _selectedServer = value;
                    OnPropertyChanged();
                    SelectedServerChanged();
                }
            }
        }

        public void SelectedServerChanged()
        {
            //do whatever you need to do when the selected server changes here...
            System.Console.WriteLine($"The selected server has changed: {SelectedServer.CountryName}");
        }

        public void ReloadServers()
        {
            var servers = DownloadServers();

            Servers.Clear();
            foreach (var server in servers)
            {
                Servers.Add(server);
            }
        }

        private List<Server> DownloadServers()
        {
            //pretend we're downloading the list of servers here...
            return new List<Server>
            {
                new Server { CityDns = "Some DNS", CountryName = "England" },
                new Server { CityDns = "Some other DNS", CountryName = "China" },
                new Server { CityDns = "Another DNS", CountryName = "United States" }
            };
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged([CallerMemberName] string propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public class Server
    {
        public string CountryName { get; set; }
        public string CityDns { get; set; }
    }
}

请注意,我没有使用ICommand进行刷新按钮单击,我通常会这样做。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59788773

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档