internal void ProcessCalculatedListUpdate(IObservableList updatedList) { var originalList = currentListElement.list; // update to the latest 'version' of this list currentListElement.list = updatedList; //var listItems = updatedList.GetItems(); var count = Math.Max(originalList.Count, updatedList.Count); for (var x = 0; x < count; x++) { var itemElement = (x < currentListElement.listItems.Count) ? currentListElement.listItems[x] : null; if (itemElement != null) { if (x < updatedList.Count) { ApplyViewModelData(itemElement.xmlElement, updatedList[x], currentListElement.DataSource, currentListElement.itemTemplate, updatedList); } else if (x >= updatedList.Count) { RemoveListItemByIndexFromCurrentList(originalList, x, currentListElement.DataSource); } } else { if (x < updatedList.Count) { RenderListItem(updatedList[x], currentListElement.DataSource, currentListElement.itemTemplate, updatedList); } } } }
public void TrackObservableList(IObservableList obj) { // No need to track items which are lazy load List <object> items = ((IObservableList)obj).ListItems; ((INotifyCollectionChanged)obj).CollectionChanged += ((RepositoryItemBase)this).ChildCollectionChanged; Parallel.ForEach(items, item => { if (item is RepositoryItemBase) { RepositoryItemBase RI = ((RepositoryItemBase)item); // Do start tracking only for item which are not already tracked if (RI.DirtyStatus == eDirtyStatus.NoTracked) { RI.StartDirtyTracking(); } RI.OnDirtyStatusChanged += this.RaiseDirtyChanged; } else { // for now we ignore list of Guids - like Agents.Tags as user cannot change the value, but if he add/remove it will be tracked if (item is Guid || item is RepositoryItemKey) { return; } throw new Exception("Error: trying to track object which is Serialized in a list but is not RepositoryItemBase " + this.GetType().FullName + " " + item.ToString()); } }); }
public CharacterManager(IChatManager chatManager, IApiManager apiManager) { this.chatManager = chatManager; this.apiManager = apiManager; OnlineCharacters = new FilteringObservableList <Character, StatusEnum>(characterList, x => x.Status, x => x != StatusEnum.Offline); chatManager.CommandReceived += HandleServerCommand; }
public TextAssociationCollection(ILogger logger, ISetting <TextAssociation[]> setting) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } _logger = logger; Items = _textAssociations.Connect() .RemoveKey() .AsObservableList(); var loader = setting.Value.Subscribe(files => { _textAssociations.Edit(innerCache => { //all files are loaded when state changes, so only add new ones var newItems = files .Where(f => !innerCache.Lookup(f.Text).HasValue) .ToArray(); innerCache.AddOrUpdate(newItems); }); }); var settingsWriter = _textAssociations.Connect() .ToCollection() .Subscribe(items => { setting.Write(items.ToArray()); }); _cleanUp = new CompositeDisposable(settingsWriter, loader, _textAssociations, Items); }
public static Func <DataTableRow, bool> BuildFilter(string searchText, IObservableList <FilterGroup> filters) { var filterQuery = BuildFilterQuery(filters); var quickSearchFilter = BuildQuickSearchFilter(searchText); return(dataList => filterQuery(dataList) && quickSearchFilter(dataList)); }
private void xmlwriteObservableList(XmlTextWriter xml, string Name, IObservableList list) { //check if the list is of Repo item or native - got a small diff when writing xml.WriteWhitespace("\n"); xml.WriteStartElement(Name); foreach (var v in list) { xml.WriteWhitespace("\n"); if (v is RepositoryItemBase) { if (!((RepositoryItemBase)v).IsTempItem) // Ignore temp items like dynamic activities or some output values if marked as temp { xmlwriteObject(xml, (RepositoryItemBase)v); } } else if (v is RepositoryItemKey) { xml.WriteElementString(v.GetType().Name, v.ToString()); } else { //TODO: use generic type write xml.WriteElementString(v.GetType().FullName, v.ToString()); } } xml.WriteWhitespace("\n"); xml.WriteEndElement(); xml.WriteWhitespace("\n"); }
public PrivacyControlViewModel(Wallet wallet, TransactionInfo transactionInfo, TransactionBroadcaster broadcaster) { _wallet = wallet; _pocketSource = new SourceList <PocketViewModel>(); _pocketSource.Connect() .Bind(out _pockets) .Subscribe(); var selected = _pocketSource.Connect() .AutoRefresh() .Filter(x => x.IsSelected); _selectedList = selected.AsObservableList(); selected.Sum(x => x.TotalBtc) .Subscribe(x => { if (_privatePocket is { }) { _privatePocket.IsWarningOpen = _privatePocket.IsSelected && _selectedList.Count > 1; } StillNeeded = transactionInfo.Amount.ToDecimal(MoneyUnit.BTC) - x; EnoughSelected = StillNeeded <= 0; });
public void BindSelection(IObservableList <ItemEx> selection) { if (Selection != null) { throw new InvalidOperationException("multiItemEditor: Selection is already set"); } this.Selection = selection; this.Selection.Connect() .TakeUntil(destroy) .ObserveOn(RxApp.MainThreadScheduler) .Bind(SelectionBinding) .Subscribe(_ => { }, ex => { MessageBox.Show(ex.ToString(), $"{nameof(MultiItemEditorViewModel)}.{nameof(BindSelection)}: selection subscription threw exception"); }); var count = this.Selection.Connect().Count().ObserveOn(RxApp.MainThreadScheduler); var selectedTags = this.Selection.Connect() .TransformMany(item => item.Tags) .GroupOn(tag => tag) .Transform(group => new CountedTag(count, group.List.Connect().Count().ObserveOn(RxApp.MainThreadScheduler), group.GroupKey) ) .DisposeMany() //.Sort() ; this.TagEditor.BindSelection(selectedTags); }
/// <summary> /// Convert nodes tree to list. /// </summary> /// <returns>The list.</returns> /// <param name="sourceNodes">Source nodes.</param> /// <param name="depth">Depth.</param> /// <param name="list">List.</param> protected virtual int Nodes2List(IObservableList <TreeNode <TItem> > sourceNodes, int depth, ObservableList <ListNode <TItem> > list) { var added_nodes = 0; foreach (var node in sourceNodes) { if (!node.IsVisible) { node.Index = -1; ResetNodesIndex(node.Nodes); continue; } list.Add(new ListNode <TItem>(node, depth)); node.Index = list.Count - 1; if (node.IsExpanded && (node.Nodes != null) && (node.Nodes.Count > 0)) { var used = Nodes2List(node.Nodes, depth + 1, list); node.UsedNodesCount = used; } else { ResetNodesIndex(node.Nodes); node.UsedNodesCount = 0; } added_nodes += 1; } return(added_nodes); }
public IObservable <IChangeSet <TObject, TKey> > Run() { return(Observable.Create <IChangeSet <TObject, TKey> >(observer => { lock (_locker) if (++_refCount == 1) { _list = _source.AsObservableList(); } var subscriber = _list.Or().SubscribeSafe(observer); return Disposable.Create(() => { subscriber.Dispose(); IDisposable listToDispose = null; lock (_locker) if (--_refCount == 0) { listToDispose = _list; _list = null; } listToDispose?.Dispose(); }); })); }
//public void Enqueue(IEnumerable<PlaybackQueueEntry> trackLocations) //{ // this._queueEntries.AddRange(trackLocations); //} public void SetTracksSource(IObservableList <Track> tracksSource) { this._playlistEntries.Clear(); this._tracksSource = tracksSource; this._tracksSource.Connect() .Transform(t => new PlaybackQueueEntry(t)) .DisposeMany() .PopulateInto(this._sourcedEntries) .DisposeWith(this._disposables); this._tracksSource .Connect() //.Transform(t => new PlaybackQueueEntry(t)) .Subscribe( null, () => { this.Clear(); }); // TODO: if the currently playing track is removed from the playlist from which its playback was started, ask if stop playback //return Task.CompletedTask; }
private void TrackObservableList(IObservableList obj) { List <object> items = ((IObservableList)obj).ListItems; ((INotifyCollectionChanged)obj).CollectionChanged += ((RepositoryItemBase)this).ChildCollectionChanged; foreach (object item in items) { if (item is RepositoryItemBase) { RepositoryItemBase RI = ((RepositoryItemBase)item); // Do start tracking only for item which are not already tracked if (RI.DirtyStatus == eDirtyStatus.NoTracked) { RI.StartDirtyTracking(); } RI.OnDirtyStatusChanged += this.RaiseDirtyChanged; } else { // for now we ignore list of Guids - like Agents.Tags as user cannot change the value, but if he add/remove it will be tracked if (item is Guid) { continue; } throw new Exception("Error: trying to track object which is Serialzied in a list but is not RepositoryItemBase " + this.GetType().FullName + " " + item.ToString()); } } }
/// <summary> /// Forwards the <paramref name="source" /> changes to the <paramref name="target" />. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source observable list.</param> /// <param name="target">The target binding list.</param> /// <param name="includeItemChanges">if set to <c>true</c> individual items' changes will be propagated to the /// <paramref name="target" /> via replacing the item completely.</param> /// <param name="includeMoves">if set to <c>true</c> move operations will be replicated to the <paramref name="target" />.</param> /// <param name="scheduler">The scheduler.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">source /// or /// target</exception> /// <exception cref="System.InvalidOperationException">Source and Target Lists must contain exactly the same element(s) at /// the exact same index position(s)</exception> public static IDisposable ForwardListChangesTo <T>( this IObservableList <T> source, IEnhancedBindingList <T> target, bool includeItemChanges = true, bool includeMoves = false, IScheduler scheduler = null) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (target == null) { throw new ArgumentNullException(nameof(target)); } if (includeMoves && (source.Except(target).Any() || target.Except(source).Any() || source.Any(element => source.IndexOf(element) != target.IndexOf(element)))) { throw new InvalidOperationException("Source and Target Lists must contain exactly the same element(s) at the exact same index position(s)"); } IObservable <IObservableListChange <T> > sourceObservable = scheduler != null ? source.ListChanges.ObserveOn(scheduler) : source.ListChanges; return(sourceObservable.ForwardListChangesTo(target, includeItemChanges, includeMoves)); }
public InventoryViewModel(IObservableList <Shop> shops) { shops.Connect() .TransformMany(s => s.Products.Select(p => new InventoryItemViewModel(s, p)), new InventoryItemViewModelEqualityComparer()) .Bind(out inventoryItems) .Subscribe(); }
/// <summary> /// Binds the results to the specified <see cref="IObservableList{T}"/>. Unlike /// binding to a <see cref="ReadOnlyObservableCollection{T}"/> which loses the /// ability to refresh items, binding to an <see cref="IObservableList{T}"/>. /// allows for refresh changes to be preserved and keeps the list read-only. /// </summary> /// <typeparam name="TObject">The type of the object.</typeparam> /// <typeparam name="TKey">The type of the key.</typeparam> /// <param name="source">The source.</param> /// <returns>The <paramref name="source"/> changeset for continued chaining.</returns> /// <exception cref="System.ArgumentNullException">source</exception> public static IObservable <IChangeSet <TObject, TKey> > BindToObservableList <TObject, TKey>( this IObservable <IChangeSet <TObject, TKey> > source, out IObservableList <TObject> observableList) { if (source == null) { throw new ArgumentNullException(nameof(source)); } // Load our source list with the change set. // Each changeset we need to convert to remove the key. var sourceList = new SourceList <TObject>(); // Output our readonly observable list, preventing the sourcelist from being editted from anywhere else. observableList = sourceList; // Return a observable that will connect to the source so we can properly dispose when the pipeline ends. return(Observable.Create <IChangeSet <TObject, TKey> >(observer => { return source .Do(changes => sourceList.Edit(editor => editor.Clone(changes.RemoveKey(editor)))) .Finally(() => sourceList.Dispose()) .SubscribeSafe(observer); })); }
private void CopyRIList(IObservableList sourceList, IObservableList targetList, List <GuidMapper> guidMappingList, bool setNewGUID) { for (int i = 0; i < sourceList.Count; i++) { object item = sourceList[i]; if (item is RepositoryItemBase) { RepositoryItemBase RI = CopyRIObject(item as RepositoryItemBase, guidMappingList, setNewGUID); if (setNewGUID) { GuidMapper mapping = new GuidMapper(); mapping.Original = RI.Guid; RI.Guid = Guid.NewGuid(); mapping.newGuid = RI.Guid; guidMappingList.Add(mapping); if ((item as RepositoryItemBase).IsSharedRepositoryInstance && (item as RepositoryItemBase).ParentGuid == Guid.Empty) { RI.ParentGuid = mapping.Original; } } targetList.Add(RI); } else { targetList.Add(item); } } }
private static void xmlReadListOfObjects(object ParentObj, XmlReader xdr, IObservableList observableList) { // read list of object into the list, add one by one, like activities, actions etc. //Fast Load if (IsObseravbleListLazyLoad(xdr.Name)) { // We can save line/col and reload later when needed string s = xdr.ReadOuterXml(); observableList.DoLazyLoadItem(s); observableList.LazyLoad = true; return; } xdr.Read(); while (xdr.NodeType != XmlNodeType.EndElement) { object item = xmlReadObject(ParentObj, xdr); if (item != null) { observableList.Add(item); } else { return; } } xdr.ReadEndElement(); }
/// <summary> /// Rebuilds the list of tabs. /// </summary> public void Rebuild() { // assume a completely new list has been set if (_oldItems != null) { // unsubscribe from change events in the old list _oldItems.ListChanged -= OnListChanged; } _oldItems = Items; // clear tab and header list Clear(); // add new list if (Items != null) { // subscribe to change events in the new list Items.ListChanged += OnListChanged; // add list objects if (Items.Count > 0) { AddRange(0, Items.Count - 1); // select first tab by default SelectTab(0, false); } } }
private void UCDataColGrid_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { //TODO: check why we come here with non matching object if (!typeof(IObservableList).IsAssignableFrom(e.NewValue.GetType())) { return; //avoid invalid cast exception } this.Dispatcher.Invoke(() => { l = (IObservableList)e.NewValue; if (l.Count == 0) { return; } // If it is input and we have only one row then no need to show the grid if (l[0].GetType() == typeof(ActInputValue) && l.Count == 1) { ValueTextBox.Visibility = System.Windows.Visibility.Visible; MainDataGrid2.Visibility = System.Windows.Visibility.Collapsed; Binding bd = new Binding("Value"); ValueTextBox.DataContext = l[0]; ValueTextBox.SetBinding(TextBox.TextProperty, bd); } else { MainDataGrid2.Visibility = System.Windows.Visibility.Visible; ValueTextBox.Visibility = System.Windows.Visibility.Collapsed; SetGridData(); } }); }
public RecentSearchCollection(ILogger logger, ISetting<RecentSearch[]> setting) { if (logger == null) throw new ArgumentNullException("logger"); _logger = logger; Items = _files.Connect() .RemoveKey() .AsObservableList(); var loader = setting.Value.Subscribe(files => { _files.Edit(innerCache => { //all files are loaded when state changes, so only add new ones var newItems = files .Where(f => !innerCache.Lookup(f.Text).HasValue) .ToArray(); innerCache.AddOrUpdate(newItems); }); }); var settingsWriter = _files.Connect() .ToCollection() .Subscribe(items => { setting.Write(items.ToArray()); }); _cleanUp = new CompositeDisposable(settingsWriter, loader, _files,Items); }
public TreeNode <TreeViewItem> FindNodeByData(object personnelT, IObservableList <TreeNode <TreeViewItem> > nodesT) { TreeNode <TreeViewItem> node = null; if (nodesT != null) { foreach (TreeNode <TreeViewItem> nodeT in nodesT) { if (nodeT == null) { continue; } try { if (nodeT.Item.Tag != null) { object tagTemp = nodeT.Item.Tag; if (tagTemp is Personnel) { //DepartmentTree.Tag由int变成了personnel,这样才能找到节点 Personnel person = tagTemp as Personnel; if (person.Id.ToString() == personnelT.ToString()) { node = nodeT; break; } } else if (nodeT.Item.Tag.ToString() == personnelT.ToString()) { node = nodeT; break; } } if (nodeT.Nodes != null) { try { node = FindNodeByData(personnelT, nodeT.Nodes); if (node != null) { break; } } catch { int I = 0; } } } catch { int It = 0; return(null); } } } return(node); }
//TODO: add sort direction flag and enable several columns public static ICollectionView AsCollectionViewOrderBy(this IObservableList list, string property) { ICollectionView cv = CollectionViewSource.GetDefaultView(list); SortDescription s = new SortDescription(property, ListSortDirection.Ascending); cv.SortDescriptions.Add(s); return(cv); }
bool SampleFilter(IObservableList <TreeNode <TreeViewItem> > nodes, Func <TreeViewItem, bool> filterFunc) { return(nodes.Count(x => { var have_visible_children = (x.Nodes == null) ? false : SampleFilter(x.Nodes, filterFunc); x.IsVisible = have_visible_children || filterFunc(x.Item); return x.IsVisible; }) > 0); }
IObservableList IObservableHierarchyList.this[long index] { get { IExplorerNode explorerNode = base[(int)index] as IExplorerNode; IObservableList list = explorerNode != null ? explorerNode.Children : null; return(list != null && list.Count != 0 ? list : null); } }
private void ObserveList(IObservableList list, string listName) { list.itemChanged += (index, item, changedField) => ListItemUpdated(list, index, item, listName, changedField); list.itemAdded += (item) => ListItemAdded(list, item, listName); list.itemRemoved += (item) => ListItemRemoved(list, item, listName); XmlLayoutTimer.AtEndOfFrame(() => MemberChanged(listName), controller); }
public static IObservableList <T> Where <T>(this IObservableList <T> self, Func <T, IObservable <bool> > predicate) { return(self .Select(item => predicate(item).Select(p => new { Item = item, Pred = p })) .Switch() .Where(x => x.Pred) .Select(x => x.Item)); }
public PagingListWithVirtualise(IObservableList <Animal> source, IObservable <IVirtualRequest> requests) { Virtualised = source.Connect() .Virtualise(requests) .AsObservableList(); _cleanUp = Virtualised; }
public SimplePagging(IObservableList <Animal> source, IObservable <IPageRequest> pager) { Paged = source.Connect() .Page(pager) .Do(changes => Console.WriteLine(changes.TotalChanges)) //added as a quick and dirty way to debug .AsObservableList(); _cleanUp = Paged; }
public ObservableListTreeModel(IObservableList list) { adapter = new TreeModelAdapter (this); sourceList = list; sourceList.ElementChanged += SourceList_ElementChanged; sourceList.ElementAdded += SourceList_ElementAdded; sourceList.ElementRemoved += SourceList_ElementRemoved; sourceList.ListChanged += SourceList_ListChanged; }
private bool ProcessesMatch(IObservableList <string> processes) { if (processes == null) { return(false); } return(processes.Items.Any(proc => proc.Contains("vMix64"))); }
private bool WindowTitlesMatch(IObservableList <string> windowtitles) { if (windowtitles == null) { return(false); } return(windowtitles.Items.Any(proc => proc.Contains("New Tab"))); }
public ObservableListTreeModel(IObservableList list) { adapter = new TreeModelAdapter(this); sourceList = list; sourceList.ElementChanged += SourceList_ElementChanged; sourceList.ElementAdded += SourceList_ElementAdded; sourceList.ElementRemoved += SourceList_ElementRemoved; sourceList.ListChanged += SourceList_ListChanged; }
public LogEntryService(ILogger logger) { _logger = logger; _readonly = _source.AsObservableList(); var loader = ReactiveLogAppender.LogEntryObservable .Buffer(TimeSpan.FromMilliseconds(250)) .Synchronize(_locker) .Subscribe(_source.AddRange); //limit size of cache to prevent too many items being created var sizeLimiter = _source.LimitSizeTo(10000).Subscribe(); // alternatively could expire by time //var timeExpirer = _source.ExpireAfter(le => TimeSpan.FromSeconds(le.Level == LogLevel.Debug ? 5 : 60), TimeSpan.FromSeconds(5), TaskPoolScheduler.Default) // .Subscribe(removed => logger.Debug("{0} log items have been automatically removed", removed.Count())); _disposer = new CompositeDisposable(sizeLimiter, _source, loader); logger.Info("Log cache has been constructed"); }
public SelectionMonitor(ILogger logger) { _logger = logger; Selected = _selected.AsObservableList(); var selectionLogger = _selected.Connect() .ToCollection() .Subscribe(collection => { logger.Debug($"{collection.Count} selected: {collection.Select(l=>l.Text).ToDelimited(Environment.NewLine)} "); }); _cleanUp = new CompositeDisposable( _selected, _recentlyRemovedFromVisibleRange, _controlSubscriber, Selected, selectionLogger, //keep recent items only up to a certain number _recentlyRemovedFromVisibleRange.LimitSizeTo(100).Subscribe()); }
internal static void IndexAccessed(IObservableList observableList, int index) { observableList.IsAccessed = true; if (BeingComputed.Count > 0) BeingComputed.Peek()(new IndexAccessNotification(observableList, index)); observableList.IsAccessed = false; }
bool SampleFilter(IObservableList<TreeNode<TreeViewItem>> nodes, Func<TreeViewItem,bool> filterFunc) { return nodes.Count(x => { var have_visible_children = (x.Nodes==null) ? false : SampleFilter(x.Nodes, filterFunc); x.IsVisible = have_visible_children || filterFunc(x.Item) ; return x.IsVisible; }) > 0; }
public ObservableListReorderableTreeModel(IObservableList list) : base(list) { }