public GraphList() : base(ListViewCachingStrategy.RecycleElement) { ItemTemplate = new DataTemplate(typeof(GraphCell)); ItemTemplate.SetBinding(GraphCell.DataProperty, "."); Rotation = 90; //BackgroundColor = MainApp.RandomColor(); SeparatorVisibility = SeparatorVisibility.None; SeparatorColor = Color.White; PropertyChanged += (sender, e) => { if (e.PropertyName == HeightProperty.PropertyName) { var whRatio = Math.Sqrt(Width / Height / MaxHWRatio); RowHeight = (int)(whRatio * Height / MinDaysOnScreen); } if (e.PropertyName == ItemsSourceProperty.PropertyName) { DataChange(ItemsSource.Cast <DayFragment>()); } }; ItemTapped += (sender, e) => { if (e.Item == null) { return; } (sender as ListView).SelectedItem = null; }; ItemAppearing += VisibilityChange(true); ItemDisappearing += VisibilityChange(false); }
private void Add(object item) { var index = ItemsSource.Cast <object>().Count() - 1; var container = GenerateContainer(item); var columnDefinition = new ColumnDefinition { Width = new GridLength(1, GridUnitType.Auto) }; ColumnDefinitions.Add(columnDefinition); Children.Add(container); SetColumn(container, index); var gridSpliter = new GridSplitter { Width = 5, ResizeBehavior = GridResizeBehavior.CurrentAndNext, VerticalAlignment = VerticalAlignment.Stretch, HorizontalAlignment = HorizontalAlignment.Right, Background = Brushes.Transparent }; Children.Add(gridSpliter); SetColumn(gridSpliter, index); }
protected virtual void SetItems() { Children.Clear(); if (ItemsSource == null) { ObservableSource = null; return; } foreach (var item in ItemsSource) { var storage = this.ItemTemplate.CreateContent() as Element; if (storage != null) { storage.BindingContext = item; } var vi = storage as View; Children.Add(vi); } var isObs = /*ItemsSource.GetType().IsGenericType &&*/ ItemsSource.GetType().GetGenericTypeDefinition() == typeof(ObservableCollection <>); if (isObs) { ObservableSource = new ObservableCollection <object>(ItemsSource.Cast <object>()); } }
private void FilterSuggestions(string text, bool openSuggestionPanel = true) { var filteredSuggestions = ItemsSource.Cast <object>(); if (text.Length > 0 && filteredSuggestions.Any()) { var property = GetSearchMember(filteredSuggestions.First().GetType()); if (property == null) { throw new MemberNotFoundException($"There's no corrisponding property the matches SearchMember value '{SearchMember}'"); } if (property.PropertyType != typeof(string)) { throw new SearchMemberPropertyTypeException($"Property '{SearchMember}' must be of type string"); } filteredSuggestions = filteredSuggestions.Where(x => property.GetValue(x).ToString().IndexOf(text, StringComparison.OrdinalIgnoreCase) >= 0).OrderByDescending(x => property.GetValue(x).ToString()); } _availableSuggestions = new ObservableCollection <object>(MaxResults > 0 ? filteredSuggestions.Take(MaxResults) : filteredSuggestions); ShowHideListbox(openSuggestionPanel); }
protected void Adapt() { if (CollectionView != null) { CollectionView.CurrentChanged -= CollectionView_CurrentChanged; CollectionView = null; } if (ComboBox != null && ItemsSource != null) { CompositeCollection comp = new CompositeCollection(); //If AllowNull == true, add a "NullItem" as the first item in the ComboBox. if (AllowNull) { comp.Add(NullItem); } //Now Add the ItemsSource. comp.Add(new CollectionContainer{Collection = ItemsSource}); //Lastly, If Selected item is not null and does not already exist in the ItemsSource, //Add it as the last item in the ComboBox if (SelectedItem != null) { List<object> items = ItemsSource.Cast<object>().ToList(); if (!items.Contains(SelectedItem)) { comp.Add(SelectedItem); } } CollectionView = CollectionViewSource.GetDefaultView(comp); if (CollectionView != null) { CollectionView.CurrentChanged += CollectionView_CurrentChanged; } ComboBox.ItemsSource = comp } }
private View GetItemView(object item) { var content = ItemTemplate.CreateContent(); if (!(content is View) && !(content is ViewCell)) { throw new InvalidViewException("Templated control must be a View or a ViewCell"); } var view = content is View ? content as View : ((ViewCell)content).View; view.BindingContext = item; if (SelectedItemCommand != null && SelectedItemCommand.CanExecute(item)) { BindSelectedItemCommand(view); } if (ShowSeparator && ItemsSource.Cast <object>().Last() != item) { var container = new StackLayout { Spacing = 0 }; container.Children.Add(view); container.Children.Add(BuildSeparator()); return(container); } return(view); }
/// <summary> /// The on flipping completed. /// </summary> /// <param name="sender"> The sender. </param> /// <param name="e"> The e. </param> protected virtual void OnFlippingCompleted(object sender, EventArgs e) { try { ClockGroup clockGroup = (ClockGroup)sender; Storyboard storyboard = (Storyboard)clockGroup.Timeline; IsFlipping = false; if (storyboard != null) { storyboard.Stop(); storyboard.Remove(); if (ItemsSource != null) { int count = ItemsSource.Cast <object>().Count(); if (SelectedIndexProxy == count - 1) { SelectedIndex = SelectedIndexProxy; } else { SelectedIndexProxy = count - 1; } } } } catch { } }
public SimpleCollection() { this.RegisterMethodParam(nameof(OnItemSelected), nameof(ItemSelected)); var stack = new StackLayout(); var scrollView = new ScrollView { Content = stack }; Content = scrollView; this.OnChanged(_ => _.ItemsSource, OnItemsSourceChanged); void OnItemsSourceChanged() { stack.Children.Clear(); ItemsSource.Cast <object>()?.ForEach(item => { var itemView = (View)ItemTemplate .Assert("ItemTemplate is null.") .CreateContent(); itemView.BindingContext = item; stack.Children.Add(itemView); itemView.OnTapped(() => ItemSelected?.Invoke(item)); }); } }
async void HandleCurrentPageChanged(object sender, EventArgs e) { var thing = SelectedItem; if (SelectedItem.Equals(ItemsSource.Cast <int>().First()) && ActiveMonthNumber > 2) { ActiveMonthNumber--; await Task.Run(() => { ((ObservableCollection <int>)ItemsSource).RemoveAt(((ObservableCollection <int>)ItemsSource).Count() - 1); }); await Task.Run(() => { ((ObservableCollection <int>)ItemsSource).Insert(0, ActiveMonthNumber - 1); }); } else if (SelectedItem.Equals(ItemsSource.Cast <int>().Last()) && ActiveMonthNumber < 11) { ActiveMonthNumber++; await Task.Run(() => { ((ObservableCollection <int>)ItemsSource).RemoveAt(0); }); await Task.Run(() => { ((ObservableCollection <int>)ItemsSource).Add(ActiveMonthNumber + 1); }); } }
public void NotifyRowTapped(int groupIndex, int inGroupIndex, Cell cell = null) { var group = TemplatedItems.GetGroup(groupIndex); bool changed = _previousGroupSelected != groupIndex || _previousRowSelected != inGroupIndex; _previousRowSelected = inGroupIndex; _previousGroupSelected = groupIndex; // A11y: Keyboards and screen readers can deselect items, allowing -1 to be possible if (cell == null && inGroupIndex != -1) { cell = group[inGroupIndex]; } // Set SelectedItem before any events so we don't override any changes they may have made. if (SelectionMode != ListViewSelectionMode.None) { SetValueCore(SelectedItemProperty, cell?.BindingContext, SetValueFlags.ClearOneWayBindings | SetValueFlags.ClearDynamicResource | (changed ? SetValueFlags.RaiseOnEqual : 0)); } cell?.OnTapped(); ItemTapped?.Invoke(this, new ItemTappedEventArgs(ItemsSource.Cast <object>().ElementAt(groupIndex), cell?.BindingContext)); }
protected virtual void SetItems() { Children.Clear(); if (ItemsSource == null) { ObservableSource = null; return; } try { foreach (var item in ItemsSource) { Children.Add(GetItemView(item)); } var isObs = ItemsSource.GetType().IsGenericType&& ItemsSource.GetType().GetGenericTypeDefinition() == typeof(ObservableCollection <>); if (isObs) { ObservableSource = new ObservableCollection <object>(ItemsSource.Cast <object>()); } } catch (Exception ex) { Debug.WriteLine($"ItemsStack SetItems fail: {ex}"); } }
/// <summary>Метод исполнения команды</summary> /// <param name="parameter">Параметр команды</param> protected void NextIndexMethod(object parameter) { if (!(ItemsSource?.Cast <object>().Skip(1).Any() == true && IntTryParse(parameter, out int addIndex))) { return; } // Количество элементов в коллекции int countItems = ItemsSource.Cast <object>().Count(); // Получение отсортированного списка положительных индексов var skipping = SkippingIndexes? // Получаем все пропускаемые индексы .Distinct() // Удаляем все дубликаты .OrderBy(i => i) // Сортируем по возрастанию .SkipWhile(i => i < 0) // Пропускаем все меньшие нуля .TakeWhile(i => i < countItems) // Забираем все меньше количества элементов .ToList() // Преобразуем в List ?? new List <int>(); // Защита на случай нулевой коллекции int countActiv = countItems - skipping.Count; // Количество элементов которые можно выбирать // Если выбирать нечего - выход if (countActiv <= 0) { SelectedIndex = -1; return; } // Получение смещения с учётом пропускаемых индексов и зацикливания addIndex = ((addIndex % countActiv) + countActiv) % countActiv; // Если смещения нет, то находим с текущего индекса первый активный if (addIndex == 0) { int index = SelectedIndex; while (skipping.BinarySearch(index) < 0) { index = (index + 1) % countItems; } SelectedIndex = index; return; } // Делаем заданное количество шагов с пропуском неактивных { int index = SelectedIndex; for (int i = 0; i < addIndex; i++) { while (skipping.BinarySearch(index) >= 0) { index = (index + 1) % countItems; } index = (index + 1) % countItems; } SelectedIndex = index; return; } }
/// <summary> /// Handle pressing of the down key to set focus on the dropdown /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void InputTextBox_KeyDown(object sender, KeyEventArgs e) { // handle pressing the down key if (e.Key == Key.Down && ItemsSource != null && ItemsSource.Cast <object>().Any()) { MatchingItemsListBox.Focus(); MatchingItemsListBox.SelectedIndex = 0; } }
private void OnItemAppearing(object sender, ItemVisibilityEventArgs e) { if (ItemAppearingCommand != null) { ItemAppearingCommand?.Execute(e.Item); } if (LoadMoreCommand != null) { if (IsGroupingEnabled) { if (PageSize == null) { var firstItem = ((IList)ItemsSource.Cast <object>().First()).Cast <object>().First(); if (e.Item == firstItem && !IsRefreshing) { LoadMoreCommand?.Execute(null); } } else { var firstItem = ((IList)ItemsSource.Cast <object>().First()).Cast <object>().First(); var totalItems = 0; foreach (var item in ItemsSource.Cast <object>()) { totalItems = totalItems + ((IList)item).Cast <object>().Count(); } if (e.Item == firstItem && !IsRefreshing & totalItems >= PageSize.Value) { LoadMoreCommand?.Execute(null); } } } else { if (PageSize == null) { if (e.Item == ItemsSource.Cast <object>().First() && !IsRefreshing) { LoadMoreCommand?.Execute(null); } } else { if (e.Item == ItemsSource.Cast <object>().First() && !IsRefreshing & ItemsSource.Cast <object>().Count() >= PageSize.Value) { LoadMoreCommand?.Execute(null); } } } } }
private void OnSelectedItemChanged(object oldValue, object newValue) { if (ItemsSource == null) { return; } SelectedIndex = ItemsSource.Cast <object>().ToList().IndexOf(newValue); SelectionChanged?.Invoke(this, new SelectionChangedEventArgs(oldValue, newValue)); }
protected override UITableViewCell GetOrCreateCellFor(UITableView tableView, NSIndexPath indexPath, object item) { UITableViewCell cell; cell = new UITableViewCell(); switch (ItemsSource.Cast <FieldControlModel>().ElementAt(indexPath.Row).Type) { case FieldType.Header: cell = new MenuHeaderCell(_cellIdentifier, (float)TableView.Frame.Width, ItemsSource.Cast <FieldControlModel>().ElementAt(indexPath.Row)); break; case FieldType.Disclosure: cell = new StandardImageCell(UITableViewCellStyle.Subtitle, _cellIdentifier, ItemsSource.Cast <FieldControlModel>().ElementAt(indexPath.Row)); cell.Accessory = UITableViewCellAccessory.DisclosureIndicator; cell.TextLabel.TextColor = Colors.Color1; break; case FieldType.MenuButton: cell = new MenuButtonCell(_cellIdentifier, (float)TableView.Frame.Width, ItemsSource.Cast <FieldControlModel>().ElementAt(indexPath.Row)); break; case FieldType.MenuItemImage: cell = new StandardImageCell(UITableViewCellStyle.Default, _cellIdentifier, ItemsSource.Cast <FieldControlModel>().ElementAt(indexPath.Row)); break; case FieldType.MenuItemSocial: cell = new MenuSocialCell(_cellIdentifier, (float)TableView.Frame.Width, ItemsSource.Cast <FieldControlModel>().ElementAt(indexPath.Row), _viewModel); break; case FieldType.Text: cell = new OnlySingleLineTextCell(UITableViewCellStyle.Default, _cellIdentifier, (float)TableView.Frame.Width, ItemsSource.Cast <FieldControlModel>().ElementAt(indexPath.Row)); break; } try { if (_selectedIndex.Row == indexPath.Row && _selectedIndex.Section == indexPath.Section) { SetCellColor(cell, Colors.Color4); } } catch (Exception ex) { } return(cell); }
// If the new item that is appearing on the screen is the last one in the // collection, we execute the LoadMoreCommand so our ViewModel knows we // want to load more data for our user from the data service. private void OnItemAppearing(object sender, ItemVisibilityEventArgs e) { ItemAppearingCommand?.Execute(e.Item); //If its the last item execute command and load more data. if (e.Item == ItemsSource.Cast <object>().Last()) { LoadMoreCommand?.Execute(null); } }
private void OnSelectedIndexChanged(object sender, EventArgs eventArgs) { if (IsItemsSourceChanging) { return; } SelectedItem = SelectedIndex <0 || SelectedIndex> Items.Count - 1 ? null : ItemsSource.Cast <object>().Skip(SelectedIndex).First(); }
// =========================================================================== // = Public Methods // =========================================================================== public void RefreshPins() { Pins.Clear(); foreach (var item in ItemsSource.Cast <ExtendedPin>()) { Pins.Add(item.AsPin()); } RaisePinsChanged(); }
private void AddFooter() { var itemsNotEmpty = ItemsSource != null && ItemsSource.Cast <object>().Any(); if (FooterTemplate != null && (ShowFooterIfEmptyItems || itemsNotEmpty) && IsFooterVisible) { var row = Rows.Count; AddHeaderOrFooter(this, FooterTemplate, row); FooterRow = row; } }
private void AdvancedListView_ItemAppearing(object sender, ItemVisibilityEventArgs e) { Entity en = e.Item as Entity; ObservableCollection <Entity> data = new ObservableCollection <Entity>(ItemsSource.Cast <Entity>()); //throw new NotImplementedException(); if (data?.LastOrDefault()?.Id == en?.Id) { GetData?.Execute(data.Count);; } }
void Handle_ItemSelected(object sender, SelectedItemChangedEventArgs e) { if (e.SelectedItem is null) { return; } var ar = ItemsSource.Cast <object>().ToArray(); var index = Array.FindIndex(ar, (obj) => obj == e.SelectedItem); SelectedIndex = index; ((ListView)sender).SelectedItem = null; }
double GetNextY(double startingOffset) { var offset = startingOffset; while (ItemsSource.Cast <object>().Any(p => _objToElement.ContainsKey(p) && Math.Abs(Canvas.GetTop(_objToElement[p]) - offset) < .1)) { offset += YOffset; } return(offset); }
/// <summary> /// Processes style changes for the terminal. /// </summary> /// <param name="oldStyle">The current style applied to the terminal.</param> /// <param name="newStyle">The new style to be applied to the terminal.</param> protected override void OnStyleChanged(Style oldStyle, Style newStyle) { base.OnStyleChanged(oldStyle, newStyle); if (ItemsSource != null) { using (DeclareChangeBlock()) { ReplaceItems(ItemsSource.Cast <object>().ToArray()); } } }
private void AdvancedListView_ItemAppearing(object sender, ItemVisibilityEventArgs e) { Entity en = e.Item as Entity; IEnumerable <Entity> list = ItemsSource.Cast <Entity>(); int dataCount = list.Count(); //throw new NotImplementedException(); if (list?.LastOrDefault()?.Id == en?.Id) { GetData?.Execute(dataCount); } }
private void EnsureItemsSourceBinding() { if (!string.IsNullOrEmpty(DisplayMemberPath) && ItemsSource != null) { var item = ItemsSource.Cast <object>().FirstOrDefault(); if (item != null && !item.GetType().GetProperties().Any(y => y.Name.Equals(Binding.Path.Path))) { throw DataGridError.DataGridComboBoxColumn.UnknownItemsSourcePath(Binding); } } }
private void EnsureItemsSourceBinding() { if (!string.IsNullOrEmpty(DisplayMemberPath) && ItemsSource != null) { var item = ItemsSource.Cast <object>().FirstOrDefault(); if (item != null && !item.GetType().GetProperties().Any(y => y.Name.Equals(Binding.Path.Path))) { throw new ArgumentException($"The ItemsSource elements do not contain a property \"{Binding.Path.Path}\". Ensure that the binding path has been set correctly."); } } }
private void ResetItems() { if (AssociatedObject == null) { return; } var menuFlyout = AssociatedObject; var itemsSrouce = ItemsSource.Cast <object>().ToList(); var customObjectToTag = CustomObjectToTag; // 前回追加分のメニューアイテムを削除 foreach (var oldItem in _addedMenuFlyoutItems) { menuFlyout.Items.Remove(oldItem); } _addedMenuFlyoutItems.Clear(); // これから配置するアイテムとの間にセパレータが必要な場合 if (IsRequireInsertSeparaterBetweenDefaultItems) { if (itemsSrouce.Count >= 1 && menuFlyout.Items.Count >= 1) { var separator = new MenuFlyoutSeparator(); menuFlyout.Items.Add(separator); _addedMenuFlyoutItems.Add(separator); } } // ItemTemplateからMenuFlyoutItem系のインスタンスを生成してMenuFlyoutSubItemに追加する foreach (var item in itemsSrouce) { var templatedContent = ItemTemplate.LoadContent(); if (templatedContent is MenuFlyoutItemBase flyoutItem) { flyoutItem.DataContext = item; flyoutItem.Tag = customObjectToTag ?? flyoutItem.Tag; menuFlyout.Items.Add(flyoutItem); _addedMenuFlyoutItems.Add(flyoutItem); } #if DEBUG else { throw new Models.Infrastructure.HohoemaExpception($"{nameof(MenuFlyoutItemsSetter)}.{nameof(ItemTemplate)} is must be MenuFlyoutItemBase inherit class."); } #endif } }
int AddGridBody(Grid grid, Size printableArea, List <Column> colNodes, Size itemsPanelMaxSize, int ix, Grid pagePanel, Panel itemsPanel) { List <object> ls = ItemsSource.Cast <object>().ToList(); for (int j = ix; j < ls.Count; j++) { //手动分页 object currentItem = ls[j]; PrintingEventArgs args = new PrintingEventArgs(); args.DataContext = currentItem; // OnBeginBuildReportItem(args); grid.RowDefinitions.Add(new RowDefinition()); // create row. Set data context. for (int i = 0; i < colNodes.Count; i++) { Column col = colNodes[i]; TextBlock tb = new TextBlock() { Margin = CellPadding, TextAlignment = col.TextAlignment }; tb.FontSize = this.FontSize; if (col.DataMember != null) { tb.SetBinding(TextBlock.TextProperty, col.DataMember); } tb.DataContext = currentItem; tb.TextWrapping = this.TextWrap; tb.VerticalAlignment = VerticalAlignment.Center; grid.Children.Add(tb); Grid.SetRow(tb, grid.RowDefinitions.Count - 1); Grid.SetColumn(tb, i); } grid.Measure(printableArea); if (grid.DesiredSize.Height > itemsPanelMaxSize.Height) { grid.RowDefinitions.RemoveAt(grid.RowDefinitions.Count - 1); int n = colNodes.Count; for (int i = 0; i < n; i++) { grid.Children.RemoveAt(grid.Children.Count - 1); } return(j); } } return(ls.Count); }
private void FilterItems() { string text = searchBar.Text; if (string.IsNullOrWhiteSpace(text) || Filter == null) { FilteredItems = ItemsSource; } else { FilteredItems = ItemsSource.Cast <object>().Where(x => x != null && Filter(x, text)).ToList(); } }