public override void Remove(RuleViewModelBase rule, bool showOnSnackbar = true) { var index = _rules.IndexOf(rule); if (index == -1) { return; } _model.Rules.Remove(rule.Rule); _rules.Remove(rule); if (!showOnSnackbar) { return; } _eventAggregator.PublishOnCurrentThread(new SnackbarMessage() { Action = smq => smq.Enqueue($"Rule \"{rule.Name}\" removed", "UNDO", () => { _rules.Insert(index, rule); _model.Rules.Add(rule.Rule); }, true) }); }
protected override void OnCreated() { using (IDataContextWrapper dataContext = _dataContextLocator()) { Group noneGroup = new Group() { Id = -1, GroupName = "None" }; GroupsList = new BindableCollection <Group>(dataContext.Table <Group>().OrderBy(g => g.GroupName).ToList()); GroupsList.Insert(0, noneGroup); if (!IsAdding) { var client = dataContext.Table <Client>().First(x => x.Id == ClientId); Forename = client.Forename; Surname = client.Surname; Birthdate = client.Birthdate; Latitude = client.Latitude; Longitude = client.Longitude; IsActive = client.IsActive; Group = client.Group ?? noneGroup; Photo = IsoStorageHelper.PhotoFromFile(client.Photo); } else { IsActive = true; Group = noneGroup; } } }
protected override void LoadState() { Forename = (string)TombstoningContainer.GetValue(TombstoningVariables.ClientEditForename); Surname = (string)TombstoningContainer.GetValue(TombstoningVariables.ClientEditSurname); Birthdate = (DateTime?)TombstoningContainer.GetValue(TombstoningVariables.ClientEditBirthdate); Longitude = (double?)TombstoningContainer.GetValue(TombstoningVariables.ClientEditLongitude); Latitude = (double?)TombstoningContainer.GetValue(TombstoningVariables.ClientEditLatitude); IsActive = (bool)TombstoningContainer.GetValue(TombstoningVariables.ClientEditIsActive); lastPhotoName = (string)TombstoningContainer.GetValue(TombstoningVariables.ClientEditLastPhotoName); Photo = ImageConverter.ConvertToImage((byte[])TombstoningContainer.GetValue(TombstoningVariables.ClientEditPhoto)); using (IDataContextWrapper dataContext = _dataContextLocator()) { Group noneGroup = new Group() { Id = -1, GroupName = "None" }; GroupsList = new BindableCollection <Group>(dataContext.Table <Group>().OrderBy(g => g.GroupName).ToList()); GroupsList.Insert(0, noneGroup); long id = (long)TombstoningContainer.GetValue(TombstoningVariables.ClientEditGroupId); Group = GroupsList.FirstOrDefault(x => x.Id == id) ?? noneGroup; } PhotoChooserTask photoChooserTask = new PhotoChooserTask(); photoChooserTask.Completed += getPhotoComplete; }
/// <summary> /// Adds in order to a list of strings if input string is not on the list, assuming all strings /// are formatted using version numbers or ip addresses (xxx.xxx.xxx.xxx) /// </summary> /// <param name="stringList">in-out string list</param> /// <param name="newString">new string to be added</param> void AddInOrder(BindableCollection <string> stringList, string newString) { if (stringList.Contains(newString)) { return; } Version newStringVersion = new Version(newString); int i = 0; while (i < stringList.Count - 1 && new Version(stringList[i]).CompareTo(newStringVersion) >= 0) { i++; } if (i <= stringList.Count - 1) { stringList.Insert(i, newString); } else { stringList.Add(newString); } }
private async void Window_Loaded(object sender, RoutedEventArgs e) { DominioDAO dominioDao = new DominioDAO(); try { var result = await dominioDao.GetAllByDomValDom("Mesa"); BindableCollection <Domino> lista = new BindableCollection <Domino>(result); //opcion por defecto combobox Domino defaultCB = new Domino { dom_val_dom = "Mesa", dom_desc = "Seleccionar", dom_val = 0 }; //insertar en la primera posición lista.Insert(0, defaultCB); estadoMesaCB.ItemsSource = lista; estadoMesaCB.SelectedIndex = 0; } catch (Exception) { MessageBox.Show("Error al cargar listado Estado al ComboBox"); } }
private async void Window_Loaded(object sender, RoutedEventArgs e) { RolDAO rolDao = new RolDAO(); try { var result = await rolDao.GetAll(); BindableCollection <Rol> lista = new BindableCollection <Rol>(result); //opcion por defecto combobox Rol defaultCB = new Rol { rol_id = 0, rol_desc = "Seleccionar", rol_index = 0 }; //insertar en la primera posición lista.Insert(0, defaultCB); PerfilCB.ItemsSource = lista; PerfilCB.SelectedIndex = 0; } catch (Exception) { MessageBox.Show("Error al cargar listado Rol"); } }
private async void Window_Loaded(object sender, RoutedEventArgs e) { CategoriaMenuDAO categoriaMenuDao = new CategoriaMenuDAO(); try { var result = await categoriaMenuDao.GetAll(); BindableCollection <CategoriaMenu> lista = new BindableCollection <CategoriaMenu>(result); //opcion por defecto combobox CategoriaMenu defaultCB = new CategoriaMenu { cat_menu_id = 0, cat_menu_nombre = "Seleccionar", cat_fase = 0 }; //insertar en la primera posición lista.Insert(0, defaultCB); categoriaCB.ItemsSource = lista; categoriaCB.SelectedIndex = 0; } catch (Exception) { MessageBox.Show("Error al cargar listado Categoría"); } }
private async void Window_Loaded(object sender, RoutedEventArgs e) { CategoriaMenuDAO categoriaMenuDao = new CategoriaMenuDAO(); MenuItemDAO menuItemDao = new MenuItemDAO(); try { //datos combobox var combobox = await categoriaMenuDao.GetAll(); BindableCollection <CategoriaMenu> lista = new BindableCollection <CategoriaMenu>(combobox); categoriaCB.ItemsSource = lista; //opcion por defecto combobox CategoriaMenu defaultCB = new CategoriaMenu { cat_menu_id = 0, cat_menu_nombre = "Seleccionar", cat_fase = 0 }; //insertar en la primera posición lista.Insert(0, defaultCB); //datos menuitem por id var menuItem = await menuItemDao.GetById(this.item_id); //obtener el nombre de la categoria string nombreCategoria = (from c in lista where c.cat_menu_id == menuItem.cat_menu_id select new { c.cat_menu_nombre }).FirstOrDefault().cat_menu_nombre; //identificar la posicion en el combobox int indice = 0; for (int i = 0; i < lista.Count; i++) { string opcion = lista[i].cat_menu_nombre; if (opcion.Equals(nombreCategoria)) { indice = i; } } categoriaCB.SelectedIndex = indice; txtNombre.Text = menuItem.item_nombre; txtDescripcion.Text = menuItem.item_desc; txtValor.Text = menuItem.item_val.ToString(); } catch (Exception) { MessageBox.Show("Error al cargar datos en Actualizar"); } }
public async void Handle(DataMessage dataMessage) { switch (dataMessage.Message) { case DataMessages.USER: switch (_userService.User.UserType) { case UserType.PERSON: // COMMENT: Profile and Logout buttons are defined in the View. They are 'static' elements visible in all cases. MenuItems.AddRange(new BindableCollection <CustomMenuItem> { new CustomMenuItem { Name = "My vehicles", OnClick = GoToMyVehicles }, new CustomMenuItem { Name = "Market", OnClick = GoToMarket }, }); PersonUserModel personUser = await _personUserService.Get(_userService.User.Username); _personUserService.PersonUser = personUser; _personUserService.PersonUser.User = _userService.User; if (personUser.PersonType == PersonType.POLICE) { MenuItems.Insert(2, new CustomMenuItem { Name = "Report accident", OnClick = GoToReportAccident }); } break; case UserType.SERVICE: MenuItems.AddRange(new BindableCollection <CustomMenuItem> { new CustomMenuItem { Name = "Add service", OnClick = GoToAddService }, new CustomMenuItem { Name = "My services", OnClick = GoToMyServices }, }); ServiceUserModel serviceUser = await _serviceUserService.Get(_userService.User.Username); _serviceUserService.ServiceUser = serviceUser; _serviceUserService.ServiceUser.User = _userService.User; break; default: break; } // COMMENT: to avoid unsafe async reach to context from both this and MyVehiclesViewModel _eventAggregator.PublishOnUIThread(new DataMessage(DataMessages.HEADER_LOADED)); break; default: break; } }
private void OnConnectionsInsertAtEventHandler(int indexAt, Connection connection) { if (_connections.All(c => c.Id != connection.Id)) { _connections.Insert(indexAt, new ConnectionViewModel(connection, _client, _inspectorTool)); } NotifyOfPropertyChange(() => ConnectionCount); }
private async void Window_Loaded(object sender, RoutedEventArgs e) { DominioDAO domDao = new DominioDAO(); MesaDAO mesaDao = new MesaDAO(); try { //datos combobox var combobox = await domDao.GetAllByDomValDom("Mesa"); BindableCollection <Domino> lista = new BindableCollection <Domino>(combobox); //opcion por defecto combobox Domino defaultCB = new Domino { dom_desc = "Seleccionar", dom_val = 0 }; //insertar en la primera posición lista.Insert(0, defaultCB); estadoMesaCB.ItemsSource = lista; //datos menuitem por id var mesa = await mesaDao.GetById(this.mesa_id); //obtener el descripcion de estado string estadoMesa = (from c in lista where c.dom_val == mesa.mesa_estado select new { c.dom_desc }).FirstOrDefault().dom_desc; //identificar la posicion en el combobox int indice = 0; for (int i = 0; i < lista.Count; i++) { string opcion = lista[i].dom_desc; if (opcion.Equals(estadoMesa)) { indice = i; } } estadoMesaCB.SelectedIndex = indice; txtMesa.Text = mesa.mesa_numero; txtCapacidad.Text = mesa.mesa_capacidad.ToString(); } catch (Exception) { MessageBox.Show("Error al cargar datos en Actualizar"); } }
private void HoldCompleted(object sender, ManipulationCompletedEventArgs e) { if (!IsActive) { return; } // stop the timer so that we don't try to re-fix this thing after moving to our // final destination. _dispatcherTimer.Stop(); var dragIndex = _currentIndex; var targetItem = _pointIndex.Get(_currentIndex); var targetLocation = targetItem.Position.Top - _scrollViewer.VerticalOffset; var transform = _dragImage.GetVerticalOffset().Transform; transform.Animate(null, targetLocation, CompositeTransform.TranslateYProperty, 200, 0, completed: () => { // reshow the hidden item if (_cardView != null) { _cardView.Opacity = 1.0; } // fade out the dragged image if (_dragImage != null) { _dragImage.Animate(null, 0.0, UIElement.OpacityProperty, 700, 0, completed: () => { _dragImage.Visibility = Visibility.Collapsed; }); } Complete(); if (dragIndex == _initialIndex) { return; } // move the dragged item if (_cardView == null) { return; } var item = (CardViewModel)_cardView.DataContext; _cardsModel.Remove(item); _cardsModel.Insert(dragIndex, item); _cardsModel.Refresh(); // fire off the event for subscribers _eventAggregator.Publish(CardPriorityChanged.Create(item.Id, dragIndex, _cardsModel.ToList())); }); IsActive = false; }
public WarehouseViewModel() { companyEntities = new CompanyEntities(); Warehouse = new BindableCollection <Warehouse>(companyEntities.Warehouse.ToList()); Warehouse.Insert(0, new Warehouse() { code = "Wybierz magazyn" }); WarehouseSelected = Warehouse.FirstOrDefault(w => w.id == Properties.Settings.Default.Warehouse); }
private void BuildTrackerConnectionProgressChanged(object sender, BuildTrackerConnectionProgressEventArgs e) { if (ShouldExitHandler(e)) { return; } foreach (var project in e.Projects) { var projectToUpdate = _projects.SingleOrDefault(p => p.Id == project.Id); if (projectToUpdate != null) { projectToUpdate.TryUpdate(project.Name); } else { _application.Dispatcher.Invoke(() => { var projectToAdd = _projectFactory.Create(SettingsId, project.Id, project.Name); var names = _projects.Select(p => p.Name).Concat(new[] { projectToAdd.Name }).OrderBy(name => name).ToArray(); var index = Array.IndexOf(names, projectToAdd.Name); _projects.Insert(index, projectToAdd); }); } } var projectsToKeep = e.Projects.Select(project => project.Id).ToArray(); var projectsToRemove = _projects.Where(project => !projectsToKeep.Contains(project.Id)).ToArray(); if (_projects.Any()) { _application.Dispatcher.Invoke(() => { _projects.RemoveRange(projectsToRemove); }); } _trie = new SuffixTrie <IProjectViewModel>(3); foreach (var project in _projects) { _trie.Add(project.Name.ToLowerInvariant(), project); } IsErrored = false; IsBusy = false; NotifyOfPropertyChange(() => HasProjects); NotifyOfPropertyChange(() => HasNoProjects); NotifyOfPropertyChange(() => IsViewable); }
public void Add(UserInterface.Permanent.ViewModel viewModel) { if (viewModel.Card.IsAttached && viewModel.Card.Is().Attachment) { var insertAt = GetEnchantmentOrEquipmentPosition(viewModel.Card); _permanents.Insert(insertAt.Value, viewModel); return; } _permanents.Add(viewModel); }
private void BuildTrackerProjectProgressChanged(object sender, BuildTrackerProjectProgressEventArgs e) { if (ShouldExitHandler(e)) { return; } foreach (var build in e.Builds) { var buildToUpdate = _builds.SingleOrDefault(b => b.Id == build.Id); if (buildToUpdate != null) { buildToUpdate.TryUpdate(e.Project.Name, build.Status, build.StartTime, build.EndTime, build.RunTime()); } else { _application.Dispatcher.Invoke(() => { var buildToAdd = _buildFactory.Create(e.Project.Name, build.Id, build.Branch, build.VersionNumber(), build.RequestedBy, build.Changes, build.Status, build.StartTime, build.EndTime, build.RunTime(), build.WebUrl); var time = new Tuple <DateTime, DateTime>(buildToAdd.EndTime ?? DateTime.MaxValue, buildToAdd.StartTime ?? DateTime.MaxValue); var times = _builds.Select(b => new Tuple <DateTime, DateTime>(b.EndTime ?? DateTime.MaxValue, b.StartTime ?? DateTime.MaxValue)).Concat(new[] { time }).OrderByDescending(t => t.Item1).ThenByDescending(t => t.Item2).ToArray(); var index = Array.IndexOf(times, time); _builds.Insert(index, buildToAdd); }); } } var buildsToKeep = e.Builds.Select(build => build.Id).ToArray(); var buildsToRemove = _builds.Where(build => !buildsToKeep.Contains(build.Id)).ToArray(); if (buildsToRemove.Any()) { _application.Dispatcher.Invoke(() => { _builds.RemoveRange(buildsToRemove); }); } IsErrored = false; IsBusy = false; NotifyOfPropertyChange(() => HasBuilds); NotifyOfPropertyChange(() => HasNoBuilds); NotifyOfPropertyChange(() => LatestBuild); NotifyOfPropertyChange(() => HasLatestBuild); NotifyOfPropertyChange(() => QueuedBuilds); NotifyOfPropertyChange(() => HasQueuedBuilds); NotifyOfPropertyChange(() => IsViewable); }
public HomeViewModel() { string categoryAll = "Tất Cả"; Category cate = new Category("0", categoryAll); //danh mục CategoryCombobox = Getlist.Get_AllCategory(); CategoryCombobox.Insert(0, cate); //danh sách sản phẩm UpdateProductsPagination(1, false, false, string.Empty); PaginationNumber = new BindableCollection <PaginationStyle>(); }
public void RegisterTask(IRunningAction action) { if (action == null) { throw new ArgumentNullException("action"); } if (!runningActions.Contains(action)) { runningActions.Insert(0, action); OnRunningActionRegistered(action); NotifyOfPropertyChange("HasRunningActions"); } }
internal void ChangeComposition(int?index, HomeportShip ship) { if (index is int i) { if (ship != null) { var fromFleet = ship.Fleet; if (fromFleet != null) { var oldIndex = fromFleet.ships.IndexOf(ship); if (fromFleet == this) { ships.Exchange(i, oldIndex); } else if (i < ships.Count) { var oldShip = ships[i]; ships.RemoveAt(i); fromFleet.ships.RemoveAt(oldIndex); ships.Insert(i, ship); fromFleet.ships.Insert(oldIndex, oldShip); } else { fromFleet.ships.Remove(ship); ships.Add(ship); } } else if (i < ships.Count) { ships[i] = ship; } else { ships.Add(ship); } } else { ships.RemoveAt(i); } } else { while (ships.Count > 1) { ships.RemoveAt(1); } } }
private void target_LogReceived(object sender, LogReceivedEventArgs e) { //if (e.Message.Level == NLog.LogLevel.Fatal && !ErrorEnabled) return; //if (e.Message.Level == NLog.LogLevel.Error && !ErrorEnabled) return; //if (e.Message.Level == NLog.LogLevel.Warn && !WarnEnabled) return; //if (e.Message.Level == NLog.LogLevel.Info && !InfoEnabled) return; //if (e.Message.Level == NLog.LogLevel.Debug && !DebugEnabled) return; //if (e.Message.Level == NLog.LogLevel.Trace && !DiagEnabled) return; if (logMessages.Count > 1000) { logMessages.RemoveAt(logMessages.Count - 1); } logMessages.Insert(0, e.Message); }
/// <summary> /// Handles the message. /// </summary> /// <param name="message">The message.</param> public void Handle(ArenaSessionAdded message) { if (arenaSessions.Count > 0) { Execute.OnUIThread( () => { using (PauseNotify.For(this)) { arenaSessions.Insert(0, message.ArenaSession); SelectedArenaSession = message.ArenaSession; RefreshStats(); } }); } }
public DatabaseModel(string name, DocumentStore documentStore) { this.name = name; this.documentStore = documentStore; Tasks = new BindableCollection <TaskModel>(x => x.Name) { new ImportTask(), new ExportTask(), new StartBackupTask(), new IndexingTask(), new SampleDataTask(), new CsvImportTask() }; if (name == null || name == Constants.SystemDatabase) { Tasks.Insert(3, new StartRestoreTask()); } SelectedTask = new Observable <TaskModel> { Value = Tasks.FirstOrDefault() }; Statistics = new Observable <DatabaseStatistics>(); Status = new Observable <string> { Value = "Offline" }; OnPropertyChanged(() => StatusImage); asyncDatabaseCommands = name.Equals(Constants.SystemDatabase, StringComparison.OrdinalIgnoreCase) ? documentStore.AsyncDatabaseCommands.ForDefaultDatabase() : documentStore.AsyncDatabaseCommands.ForDatabase(name); DocumentChanges.Select(c => Unit.Default).Merge(IndexChanges.Select(c => Unit.Default)) .SampleResponsive(TimeSpan.FromSeconds(2)) .Subscribe(_ => RefreshStatistics()); databaseChanges.ConnectionStatusCahnged += (sender, args) => { ApplicationModel.Current.Server.Value.SetConnected(((IDatabaseChanges)sender).Connected); UpdateStatus(); }; RefreshStatistics(); }
private async void Window_Loaded(object sender, RoutedEventArgs e) { CatalogoProductoDAO catalogoDao = new CatalogoProductoDAO(); ProveedorDAO proveedorDao = new ProveedorDAO(); try { //insertar datos al combobox CatalogoCB var catalogoResult = await catalogoDao.GetAll(); BindableCollection <CatalogoProducto> listaCatalogo = new BindableCollection <CatalogoProducto>(catalogoResult); //opcion por defecto combobox CatalogoProducto defaultCB1 = new CatalogoProducto { cat_prod_id = 0, nombre = "Seleccionar" }; //insertar en la primera posición listaCatalogo.Insert(0, defaultCB1); CatalogoCB.ItemsSource = listaCatalogo; CatalogoCB.SelectedIndex = 0; //insertar datos al combobox ProveedorCB var proveedorResult = await proveedorDao.GetAll(); BindableCollection <Proveedor> listaProveedor = new BindableCollection <Proveedor>(proveedorResult); //opcion por defecto combobox Proveedor defaultCB2 = new Proveedor { proveedor_id = 0, nombre = "Seleccionar" }; //insertar en la primera posición listaProveedor.Insert(0, defaultCB2); ProveedorCB.ItemsSource = listaProveedor; ProveedorCB.SelectedIndex = 0; } catch (Exception) { MessageBox.Show("Error al cargar listados"); } }
private void AddToAnimeList(AnimeModel animeToAdd) { // Saves the anime to the database // Sets the id of the anime to the database version // This ensures it has the correct id to delete or edit later if needed SQLiteDataAccess.SaveAnime(animeToAdd); animeToAdd.Id = SQLiteDataAccess.GetLastRecord().Id; // Inserts an anime in the first index of the bindable collection // This makes it appear at the top of the data grid _animes.Insert(0, animeToAdd); if (SortType != SortMethod.All) { SortAnimeByStatus(); } NotifyOfPropertyChange(() => TotalAnimes); }
void PostComment(string contents) { if (IsLoadingComments) { return; } CanPostComment = false; PhotoComment comment = new PhotoComment(); comment.Contents = contents; comment.CreatedBy = SecurityContext.Current.User.Name; comment.PhotoId = Id; comment.AlbumId = AlbumId; PhotoServiceClient svc = new PhotoServiceClient(); try { svc.CreateCommentCompleted += (sender, e) => { if (e.Error != null) { e.Error.Handle(); } else { if (_comments != null) { _comments.Insert(0, MapToPhotoCommentViewModel(e.Result)); } } CanPostComment = true; CommentContents = string.Empty; NotifyOfPropertyChange(() => HasComment); }; svc.CreateCommentAsync(comment); } catch { CanPostComment = true; } }
public DatabaseModel(string name, DocumentStore documentStore) { this.name = name; this.documentStore = documentStore; Tasks = new BindableCollection<TaskModel>(x => x.Name) { new ImportTask(), new ExportTask(), new StartBackupTask(), new IndexingTask(), new SampleDataTask(), new CsvImportTask() }; if (name == null || name == Constants.SystemDatabase) Tasks.Insert(3, new StartRestoreTask()); SelectedTask = new Observable<TaskModel> { Value = Tasks.FirstOrDefault() }; Statistics = new Observable<DatabaseStatistics>(); Status = new Observable<string> { Value = "Offline" }; asyncDatabaseCommands = name.Equals(Constants.SystemDatabase, StringComparison.OrdinalIgnoreCase) ? documentStore.AsyncDatabaseCommands.ForDefaultDatabase() : documentStore.AsyncDatabaseCommands.ForDatabase(name); DocumentChanges.Select(c => Unit.Default).Merge(IndexChanges.Select(c => Unit.Default)) .SampleResponsive(TimeSpan.FromSeconds(2)) .Subscribe(_ => RefreshStatistics(), exception => ApplicationModel.Current.Server.Value.IsConnected.Value = false); databaseChanges.ConnectionStatusCahnged += (sender, args) => { ApplicationModel.Current.Server.Value.IsConnected.Value = (sender as IDatabaseChanges).Connected; OnPropertyChanged(() => ApplicationModel.Current.Server.Value.IsConnected); UpdateStatus(); }; RefreshStatistics(); }
public static void Replace <T>(this BindableCollection <T> lst, Func <T, bool> expr, T newItem) { for (var i = lst.Count - 1; i >= 0; i--) { if (expr(lst[i])) { lst.RemoveAt(i); if (i <= lst.Count) { lst.Insert(i, newItem); } else { lst.Add(newItem); } // lst[i] = newItem; break; } } }
private void OnHerdAgetDiscovery(HerdAgentInfo newHerdAgent) { int i = 0; while (i < HerdAgentList.Count - 1 && HerdAgentList[i].NumProcessors >= newHerdAgent.NumProcessors) { i++; } if (i <= HerdAgentList.Count - 1) { HerdAgentList.Insert(i, new HerdAgentViewModel(newHerdAgent)); } else { HerdAgentList.Add(new HerdAgentViewModel(newHerdAgent)); } NotifyOfPropertyChange(() => HerdAgentList); }
public ShellViewModel() { Messages = new BindableCollection<LogMessage>(); SelectedMessages = new BindableCollection<LogMessage>(); IgnoredProcesses = new BindableCollection<string>(); IgnoredText = new BindableCollection<string>(); _listener = new WpfTraceListener(); _listener.CollectionChanged += (sender, e) => { if (e.Action != NotifyCollectionChangedAction.Add) return; var logMessage = (LogMessage) e.NewItems[0]; if(FilterMessage(logMessage)) { IgnoredMessages += 1; return; } Messages.Insert(0, logMessage); }; }
/// <summary> /// Provides the observer with new data. /// </summary> /// <param name="value">The current notification information.</param> public void OnNext(Notification <ConnectionSettings>[] value) { if (_isDisposed) { // Do nothing if disposed (pattern practice). return; } var currentConnections = Connections.ToDictionary(connection => connection.SettingsId, connection => connection); foreach (var settings in Notification <ConnectionSettings> .GetPayloads(value, NotificationType.Removed, s => currentConnections.ContainsKey(s.Id))) { var connectionToRemove = currentConnections[settings.Id]; _application.Dispatcher.Invoke(() => { _connections.Remove(connectionToRemove); }); } foreach (var settings in Notification <ConnectionSettings> .GetPayloads(value, NotificationType.Updated, s => currentConnections.ContainsKey(s.Id))) { var connectionToUpdate = currentConnections[settings.Id]; connectionToUpdate.SettingsName = settings.Name; } foreach (var settings in Notification <ConnectionSettings> .GetPayloads(value, NotificationType.Added, s => !currentConnections.ContainsKey(s.Id))) { _application.Dispatcher.Invoke(() => { var connectionToAdd = _connectionViewModelStrategy.Create(settings); var names = _connections.Select(c => c.SettingsName).Concat(new[] { connectionToAdd.SettingsName }).OrderBy(name => name).ToArray(); var index = Array.IndexOf(names, connectionToAdd.SettingsName); _connections.Insert(index, connectionToAdd); }); } }
public ParcelViewModel() { companyEntities = new CompanyEntities(); Status = new BindableCollection <Status>(companyEntities.Status.ToList()); TypeOfParcel = new BindableCollection <TypeOfParcel>(companyEntities.TypeOfParcel.ToList()); Warehouse = new BindableCollection <Warehouse>(companyEntities.Warehouse.ToList()); Status.Insert(0, new Status() { status1 = "Wybierz status" }); StatusSelected = Status.FirstOrDefault(); TypeOfParcel.Insert(0, new TypeOfParcel() { type = "Wybierz typ" }); TypeOfParcelSelected = TypeOfParcel.FirstOrDefault(); Warehouse.Insert(0, new Warehouse() { code = "Wybierz magazyn" }); WarehouseSelected = Warehouse.FirstOrDefault(w => w.id == Properties.Settings.Default.Warehouse); }
public VersionsManagementViewModel( ConfigService configService, GamePathService gamePathService, VersionService versionService, IWindowManager windowManager) { _windowManager = windowManager; _config = configService.Entries; _gamePathService = gamePathService; _versionService = versionService; Versions = new BindableCollection <Version>(); // OnVersionsLoaded _versionService.Loaded += hasAny => { string selectedVersion = _config.SelectedVersion; Versions.Clear(); Versions.AddRange(_versionService.GetAll()); SelectedVersionID = _versionService.Has(selectedVersion) ? selectedVersion : Versions.FirstOrDefault()?.ID; }; // OnVersionCreated _versionService.Created += version => { Versions.Insert(0, version); SelectedVersionID = version.ID; }; // OnVersionDeleted _versionService.Deleted += version => { Versions.Remove(version); SelectedVersionID ??= Versions.FirstOrDefault()?.ID; }; }