Socket 简易静态服务器 WPF MVVM模式(三)
ViewModels类
这个类其实就是个大杂烩,什么都可以用
这个类没有什么东西,最多的就是写一下xaml页面的逻辑控制,开启关闭监听
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Web.Script.Serialization; using System.Windows; using System.Windows.Input; using 简易静态服务器.Code; using 简易静态服务器.Commands; using 简易静态服务器.Models; namespace 简易静态服务器.ViewModels { public class MainViewModels : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected void OnChanged(PropertyChangedEventArgs args) => PropertyChanged?.Invoke(this, args); private ObservableCollection<MainClass> mainclass=new ObservableCollection<MainClass>(); public ObservableCollection<MainClass> MainClass { get { return mainclass; } set { mainclass = value; OnChanged(new PropertyChangedEventArgs("MainClass")); } } private string prot; private string fileurl; private bool input; private bool run; private string ip; public bool Run { get => run; set { run = value; OnChanged(new PropertyChangedEventArgs("Run")); } } public bool Input { get => input; set { input = value;OnChanged(new PropertyChangedEventArgs("Input")); } } public string IP { get => ip; set { ip = value;OnChanged(new PropertyChangedEventArgs("IP")); } } public string Prot { get { return prot; } set { prot = value; OnChanged(new PropertyChangedEventArgs("Prot")); } } public string FileUrl { get { return fileurl; } set { fileurl = value; OnChanged(new PropertyChangedEventArgs("FileUrl")); } } private Server server; private IPAddress IPadd; private int IPprot; public MainViewModels() { server = new Server(); server.OnStocketStringChange += Server_OnStocketStringChange; MainClass = new ObservableCollection<MainClass>(); run = true; input = true; } public ICommand StatrCommand { get { return new MainCommand(Exectue, CanExectue); } } public ICommand StopCommand { get { return new MainCommand(Exectue2, CanExectue2); } } private bool CanExectue2(object arg) { if (!run) { return true; } return false; } private void Exectue2() { server.Stop(); run = true; input = true; } private void Server_OnStocketStringChange(string sender) { Application.Current.Dispatcher.Invoke(() => { MainClass.Add(new Models.MainClass() { StocketSting = sender }); }); } private bool CanExectue(object obj) { if (run) { if (IPAddress.TryParse(IP, out IPadd) && int.TryParse(Prot, out IPprot) && System.IO.Directory.Exists(FileUrl)) return true; else return false; } return false; } private void Exectue() { server.Start(IPadd,IPprot,10,FileUrl); run = false; input = false; } } }
不过也有一点需要注意的 就是跨线程更新UI 这个地方MVVM报错的比较多