private void addRow(DataGridCell cell) { int ID = dataGridView.Rows.Count + 1; string[] row = new string[] {ID.ToString(), cell.bundleID, cell.executeName, cell.scheme}; dataGridView.Rows.Add(row); dataGridView.Rows[0].ReadOnly = false; }
public static int GetRowIndex(DataGridCell dataGridCell) { // Use reflection to get DataGridCell.RowDataItem property value. PropertyInfo rowDataItemProperty = dataGridCell.GetType().GetProperty("RowDataItem", BindingFlags.Instance | BindingFlags.NonPublic); DataGrid dataGrid = GetDataGridFromChild(dataGridCell); return dataGrid.Items.IndexOf(rowDataItemProperty.GetValue(dataGridCell, null)); }
protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem) { var binding = new Binding(bindingPath); var textBlock = new TextBlock(); textBlock.SetBinding(TextBlock.TextProperty, binding); textBlock.Margin = new Thickness(0, 0, 2, 0); return BuildElement(textBlock); }
protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) { var binding = new Binding(bindingPath) {Mode = BindingMode.TwoWay, Converter = new DateTimeConverter()}; var textBlock = new TextBox(); textBlock.SetBinding(TextBox.TextProperty, binding); textBlock.Margin = new Thickness(0, 0, 2, 0); return BuildElement(textBlock); }
/// <summary> /// AutomationPeer for DataGridCell. /// This automation peer should not be part of the automation tree. /// It should act as a wrapper peer for DataGridCellItemAutomationPeer /// </summary> /// <param name="owner">DataGridCell</param> public DataGridCellAutomationPeer(DataGridCell owner) : base(owner) { if (owner == null) { throw new ArgumentNullException("owner"); } UpdateEventSource(); }
/// <summary> /// Creates the visual tree for text based cells. /// </summary> protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem) { TextBlock textBlock = new TextBlock(); SyncProperties(textBlock); ApplyStyle(/* isEditing = */ false, /* defaultToElementStyle = */ false, textBlock); ApplyBinding(textBlock, TextBlock.TextProperty); return textBlock; }
protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem) { var control = new ContentControl(); var binding = CreateBinding(); BindingOperations.SetBinding(control, ContentPresenter.ContentProperty, binding); var template = GetDisplayTemplate(dataItem); control.ContentTemplate = template; return control; }
protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) { var numericEditor = new DoubleUpDown(); numericEditor.Minimum = Minimum; numericEditor.Maximum = Maximum; numericEditor.Increment = Increment; numericEditor.FormatString = FormatString; var sourceBinding = this.Binding as System.Windows.Data.Binding; var binding = new System.Windows.Data.Binding(); binding.Path = sourceBinding.Path; binding.Converter = new TargetTypeConverter(); numericEditor.SetBinding(DoubleUpDown.ValueProperty, binding); return numericEditor; }
private void UpdateCurrentCell(DataGridCell cell, bool isFocusWithinCell) { if (isFocusWithinCell) { // Focus is within the cell, make it the current cell. CurrentCellContainer = cell; } else if (!IsKeyboardFocusWithin) { // Focus moved outside the DataGrid, so clear out the current cell. CurrentCellContainer = null; } // Focus is within the DataGrid but not within this particular cell. // Assume that focus is moving to another cell, and that cell will update // the current cell. }
public static void SetTextBoxController(DataGridCell element, bool value) { element.SetValue(TextBoxControllerProperty, value); }
/// <summary> /// Creates the visual tree for text based cells. /// </summary> protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) { ComboBox comboBox = new ComboBox(); ApplyStyle(/* isEditing = */ true, /* defaultToElementStyle = */ false, comboBox); ApplyColumnProperties(comboBox); return comboBox; }
/// <summary> /// When overridden in a derived class, gets an editing element that is bound to the column's <see cref="P:System.Windows.Controls.DataGridBoundColumn.Binding"/> property value. /// </summary> /// <param name="cell">The cell that will contain the generated element.</param> /// <param name="dataItem">The data item represented by the row that contains the intended cell.</param> /// <returns> /// A new editing element that is bound to the column's <see cref="P:System.Windows.Controls.DataGridBoundColumn.Binding"/> property value. /// </returns> protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) { #if !SILVERLIGHT _isEditing = false; #endif if(!string.IsNullOrEmpty(Field)) { var codedValueSources = Utilities.DynamicCodedValueSource.GetCodedValueSources(LookupField, FieldInfo, dataItem, DynamicCodedValueSource, nullableSources); if (codedValueSources != null) { ComboBox box = new ComboBox { Margin = new Thickness(4.0), VerticalAlignment = VerticalAlignment.Center, VerticalContentAlignment = VerticalAlignment.Center, DisplayMemberPath = "DisplayName" }; if (!string.IsNullOrEmpty(LookupField) && DynamicCodedValueSource != null) { // Item Source Binding lookupConverter.LookupField = this.LookupField; lookupConverter.Field = this.FieldInfo; lookupConverter.NullableSources = this.nullableSources; Binding binding = new Binding(); binding.Mode = BindingMode.OneWay; binding.Converter = lookupConverter; binding.ConverterParameter = DynamicCodedValueSource; box.SetBinding(ComboBox.ItemsSourceProperty, binding); // Selected Item Binding selectedConverter.Field = Field; selectedConverter.LookupField = LookupField; selectedConverter.NullableSources = this.nullableSources; Binding selectedBinding = new Binding(); selectedBinding.Mode = BindingMode.OneWay; selectedBinding.Converter = selectedConverter; selectedBinding.ConverterParameter = this.DynamicCodedValueSource; box.SetBinding(ComboBox.SelectedItemProperty, selectedBinding); box.SelectionChanged += box_SelectionChanged; } return box; } else if(FieldInfo.Type == Client.Field.FieldType.Date) { DateTimePicker dtp = new DateTimePicker { Margin = new Thickness(4.0), VerticalAlignment = VerticalAlignment.Center, VerticalContentAlignment = VerticalAlignment.Center, DateTimeFormat = this.DateTimeFormat, DateTimeKind = this.DateTimeKind, Language = cell.Language }; Binding selectedBinding = #if SILVERLIGHT new Binding(Field); #else new Binding("Attributes["+Field+"]"); if (FieldDomainUtils.IsDynamicDomain(FieldInfo, LayerInfo)) { selectedBinding.ValidationRules.Add(new DynamicRangeDomainValidationRule() { ValidationStep = ValidationStep.ConvertedProposedValue, Field = FieldInfo, LayerInfo = LayerInfo, Graphic = dataItem as Graphic }); } #endif selectedBinding.Mode = BindingMode.TwoWay; selectedBinding.ValidatesOnExceptions = true; selectedBinding.NotifyOnValidationError = true; dtp.SetBinding(DateTimePicker.SelectedDateProperty, selectedBinding); return dtp; } else { TextBox box = new TextBox { Margin = new Thickness(4.0), VerticalAlignment = VerticalAlignment.Center, VerticalContentAlignment = VerticalAlignment.Center, }; box.MaxLength = Field.Length; Binding binding = #if SILVERLIGHT new Binding(Field); binding.Mode = BindingMode.TwoWay; binding.ValidatesOnExceptions = true; binding.NotifyOnValidationError = true; binding.Converter = emptyStringToNullConverter; #else new Binding("Attributes["+Field+"]"); binding.Mode = BindingMode.TwoWay; stringToPrimitiveTypeConverter.FieldType = FieldInfo.Type; binding.Converter = stringToPrimitiveTypeConverter; // Validates that the value entered into the text box can be // converted to the corrected field type without error. // if value cannot be converted to the correct type validation // error will be triggered based on binding trigger below. binding.ValidationRules.Add(new FeatureValidationRule() { ValidationStep = ValidationStep.ConvertedProposedValue, FieldType = FieldInfo.Type, Nullable = FieldInfo.Nullable }); if (FieldDomainUtils.IsDynamicDomain(FieldInfo, LayerInfo)) { binding.ValidationRules.Add(new DynamicRangeDomainValidationRule() { ValidationStep = ValidationStep.ConvertedProposedValue, Field = FieldInfo, LayerInfo = LayerInfo, Graphic = dataItem as Graphic }); } // Build a data trigger to show the validation error i.e. red outline around textbox // with message content in tooltip. var setterBinding = new Binding("(Validation.Errors)[0].ErrorContent"); setterBinding.RelativeSource = RelativeSource.Self; var setter = new Setter(); setter.Property = TextBox.ToolTipProperty; setter.Value = setterBinding; var trigger = new Trigger(); trigger.Property = Validation.HasErrorProperty; trigger.Value = true; trigger.Setters.Add(setter); var style = new Style(typeof(TextBox)); style.Triggers.Add(trigger); box.Style = style; #endif box.SetBinding(TextBox.TextProperty, binding); return box; } } return new TextBlock(); // Should never reach this line. }
/// <summary> /// Creates the visual tree for cells. /// </summary> protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem) { TextBlock outerBlock = new TextBlock(); Hyperlink link = new Hyperlink(); InlineUIContainer inlineContainer = new InlineUIContainer(); ContentPresenter innerContentPresenter = new ContentPresenter(); outerBlock.Inlines.Add(link); link.Inlines.Add(inlineContainer); inlineContainer.Child = innerContentPresenter; link.TargetName = TargetName; ApplyStyle(/* isEditing = */ false, /* defaultToElementStyle = */ false, outerBlock); ApplyBinding(link, Hyperlink.NavigateUriProperty); ApplyContentBinding(innerContentPresenter, ContentPresenter.ContentProperty); return outerBlock; }
private void SelectAndEditOnFocusMove(KeyEventArgs e, DataGridCell oldCell, bool wasEditing, bool allowsExtendSelect, bool ignoreControlKey) { DataGridCell newCell = GetCellForSelectAndEditOnFocusMove(); if ((newCell != null) && (newCell.DataGridOwner == this)) { if (ignoreControlKey || ((e.KeyboardDevice.Modifiers & ModifierKeys.Control) == 0)) { if (ShouldSelectRowHeader && allowsExtendSelect) { HandleSelectionForRowHeaderAndDetailsInput(newCell.RowOwner, /* startDragging = */ false); } else { HandleSelectionForCellInput(newCell, /* startDragging = */ false, allowsExtendSelect, /* allowsMinimalSelect = */ false); } } // If focus moved to a new cell within the same row that didn't // decide on its own to enter edit mode, put it in edit mode. if (wasEditing && !newCell.IsEditing && (oldCell.RowDataItem == newCell.RowDataItem)) { BeginEdit(e); } } }
/// <summary> /// When overridden in a derived class, gets an editing element that is bound to the column's <see cref="P:System.Windows.Controls.DataGridBoundColumn.Binding"/> property value. /// </summary> /// <param name="cell">The cell that will contain the generated element.</param> /// <param name="dataItem">The data item represented by the row that contains the intended cell.</param> /// <returns> /// A new editing element that is bound to the column's <see cref="P:System.Windows.Controls.DataGridBoundColumn.Binding"/> property value. /// </returns> protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) { #if !SILVERLIGHT _isEditing = false; #endif ComboBox box = new ComboBox() { Margin = new Thickness(4.0), VerticalAlignment = VerticalAlignment.Center, VerticalContentAlignment = VerticalAlignment.Center, DisplayMemberPath = "DisplayName" }; if (!string.IsNullOrEmpty(Field) && this.CodedValueSources != null) { // Item Source Binding Binding binding = new Binding(); binding.Mode = BindingMode.OneWay; binding.Converter = lookupConverter; binding.ConverterParameter = this.CodedValueSources; box.SetBinding(ComboBox.ItemsSourceProperty, binding); // Selected Item Binding selectedConverter.Field = Field; Binding selectedBinding = new Binding(); selectedBinding.Mode = BindingMode.OneWay; selectedBinding.Converter = selectedConverter; selectedBinding.ConverterParameter = this.CodedValueSources; box.SetBinding(ComboBox.SelectedItemProperty, selectedBinding); box.SelectionChanged += box_SelectionChanged; } return box; }
private bool InvalidateCellsPanelOnColumnChange() { if (InternalItemsHost == null) { return(false); } bool isVirtualizing = VirtualizingStackPanel.GetIsVirtualizing(this); List <RealizedColumnsBlock> blockList = null; if (isVirtualizing && !DataGridOwner.InternalColumns.RebuildRealizedColumnsBlockListForVirtualizedRows) { blockList = DataGridOwner.InternalColumns.RealizedColumnsBlockListForVirtualizedRows; } else if (!isVirtualizing && !DataGridOwner.InternalColumns.RebuildRealizedColumnsBlockListForNonVirtualizedRows) { blockList = DataGridOwner.InternalColumns.RealizedColumnsBlockListForNonVirtualizedRows; } // either RebuildRealizedColumnsBlockListForNonVirtualizedRows or RebuildRealizedColumnsBlockListForVirtualizedRows is true if (blockList == null) { return(true); } IList children = InternalItemsHost.Children; int lastRealizedColumnBlockIndex = 0, lastChildrenIndex = 0; int childrenCount = children.Count; int blockListCount = blockList.Count; int allColumnsCount = DataGridOwner.Columns.Count; bool foundInRealizedColumns, foundInCells; for (int i = 0; i < allColumnsCount; i++) { foundInRealizedColumns = false; foundInCells = false; // find column in RealizedColumns if (lastRealizedColumnBlockIndex < blockListCount) { RealizedColumnsBlock rcb = blockList[lastRealizedColumnBlockIndex]; if ((rcb.StartIndex <= i) && (i <= rcb.EndIndex)) { foundInRealizedColumns = true; // reached end of this block, start from next block if (i == rcb.EndIndex) { lastRealizedColumnBlockIndex++; } } } // find column in Children if (lastChildrenIndex < childrenCount) { DataGridCell cell = children[lastChildrenIndex] as DataGridCell; if (DataGridOwner.Columns[i] == cell.Column) { foundInCells = true; lastChildrenIndex++; } } // if found in one but not the other or reached end of either list. bool reachedEndofBlockList = (lastRealizedColumnBlockIndex == blockListCount); bool reachedEndofChildrenList = (lastChildrenIndex == childrenCount); if ((foundInCells != foundInRealizedColumns) || (reachedEndofBlockList != reachedEndofChildrenList)) { return(true); } else if (reachedEndofBlockList == true) { //reached end of both columns and children lists break; } } return(false); }
/// <summary> /// Creates the visual tree for decimal based cells. /// This happens every time a cell goes into edit mode. /// </summary> protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) { return(GenerateDecimalTextBox(true, cell)); }
protected virtual void m_mthHandleCellChanged(DataGridCell p_dgcOldCell, DataGridCell p_dgcNewCell) { }
protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) { throw new InvalidOperationException(); }
private void FillForm() { ATextBox.Value = col.collar.u_mass_corr_fact_a.v; AErrorTextBox.Value = col.collar.u_mass_corr_fact_a.err; BTextBox.Value = col.collar.u_mass_corr_fact_b.v; BErrorTextBox.Value = col.collar.u_mass_corr_fact_b.err; DataGridViewRow types = new DataGridViewRow(); poison = NCC.CentralizedState.App.DB.PoisonRods.GetList(); for (int i = 0; i < poison.Count; i++) { list.Add(poison[i].rod_type); } //For now, only one row. //for (int j = 0; j < list.Count; j++) //{ DataGridViewRow row = new DataGridViewRow(); row.CreateCells(dataGridView1); DataGridCell combo = new DataGridCell(); combo.ColumnNumber = 0; combo.RowNumber = 0; DataGridViewComboBoxCell cel = new DataGridViewComboBoxCell(); int j = 0; foreach (string s in list) { cel.Items.Add(s); } row.Cells[0] = cel; row.Cells[0].Value = list[j]; row.Cells[1].ValueType = typeof(int); if (j == 0) { row.Cells[1].Value = col.collar.number_calib_rods; //Make them all G type } else { row.Cells[1].Value = 0; } row.Cells[2].ValueType = typeof(double); row.Cells[2].Value = col.collar.poison_absorption_fact[j]; row.Cells[3].ValueType = typeof(double); row.Cells[3].Value = col.collar.poison_rod_a[j].v; row.Cells[4].ValueType = typeof(double); row.Cells[4].Value = col.collar.poison_rod_a[j].err; row.Cells[5].ValueType = typeof(double); row.Cells[5].Value = col.collar.poison_rod_b[j].v; row.Cells[6].ValueType = typeof(double); row.Cells[6].Value = col.collar.poison_rod_b[j].err; row.Cells[7].ValueType = typeof(double); row.Cells[7].Value = col.collar.poison_rod_c[j].v; row.Cells[8].ValueType = typeof(double); row.Cells[8].Value = col.collar.poison_rod_c[j].err; dataGridView1.Rows.Add(row); StoreChanges(); //} /*for (int k = list.Count; k < 10; k++) * { * DataGridViewRow row = new DataGridViewRow(); * row.CreateCells(dataGridView1); * DataGridCell combo = new DataGridCell(); * combo.ColumnNumber = 0; * combo.RowNumber = k; * DataGridViewComboBoxCell cel = new DataGridViewComboBoxCell(); * foreach (string s in list) * { * cel.Items.Add(s); * } * row.Cells[0] = cel; * row.Cells[1].ValueType = typeof(int); * row.Cells[1].Value = 0; * row.Cells[2].ValueType = typeof(double); * row.Cells[2].Value = 0; * row.Cells[3].ValueType = typeof(double); * row.Cells[3].Value = 0; * row.Cells[4].ValueType = typeof(double); * row.Cells[4].Value = 0; * row.Cells[5].ValueType = typeof(double); * row.Cells[5].Value = 0; * row.Cells[6].ValueType = typeof(double); * row.Cells[6].Value = 0; * row.Cells[7].ValueType = typeof(double); * row.Cells[7].Value = 0; * row.Cells[8].ValueType = typeof(double); * row.Cells[8].Value = 0; * dataGridView1.Rows.Add(row); * * }*/ SetHelp(); }
private void dataGrid_KeyUp(object sender, KeyEventArgs e) { int counter = 0; Boolean itemFound = false; DataGridCell d = e.OriginalSource as DataGridCell; if (e.Key == Key.Enter) { if (d.Foreground.ToString() == "#FFFFFFFF") { foreach (Data item in dataGrid.ItemsSource) { if (item.suffix[0] == 'i') { int numOfLines = (int)Char.GetNumericValue(item.suffix[1]); for (int i = counter + 1; i < (counter + numOfLines + 1); i++) { rows.Insert(i, new Data { lineNum = i, data = "", suffix = "=====" }); } itemFound = true; break; } else if (item.suffix[0] == 'x') { if (item.suffix == "x") { hiddenRows.Add(rows[counter + 1]); rows.RemoveAt(counter + 1); rows.Insert(counter + 1, new Data { lineNum = counter + 1, data = "hidden line", suffix = "=====" }); } else { int numOfLines = (int)Char.GetNumericValue(item.suffix[1]); for (int i = counter + 1; i < (counter + numOfLines + 1); i++) { hiddenRows.Add(rows[i]); } for (int j = counter; j < (counter + numOfLines); j++) { rows.RemoveAt(counter + 1); } rows.Insert(counter + 1, new Data { lineNum = counter + 1, data = "hidden line", suffix = "=====" }); } itemFound = true; break; } else if (item.suffix[0] == 's' && item.data == "hidden line") { if (item.suffix == "s") { rows.Insert(counter + 1, hiddenRows[(hiddenRows.Count() - 1)]); hiddenRows.RemoveAt(hiddenRows.Count() - 1); if (hiddenRows.Count() == 0) { rows.RemoveAt(counter); } } else { int numOfLines = (int)Char.GetNumericValue(item.suffix[1]); int counterH = 0; for (int i = counter + 1; i < (counter + numOfLines + 1); i++) { rows.Insert(i, hiddenRows[(hiddenRows.Count() - numOfLines + counterH)]); counterH++; } for (int i = counter + 1; i < (counter + numOfLines + 1); i++) { hiddenRows.RemoveAt(hiddenRows.Count() - 1); } if (hiddenRows.Count() == 0) { rows.RemoveAt(counter); } } itemFound = true; break; } else if (item.suffix[0] == 'a') { if (copyRows.Count() != 0) { int numOfLines = copyRows.Count(); int counterH = 0; for (int i = counter + 1; i < (counter + numOfLines + 1); i++) { string myData = copyRows[(copyRows.Count() - numOfLines + counterH)].data; rows.Insert(i, new Data { lineNum = counter + 1, data = myData, suffix = "=====" }); counterH++; } copyRows.Clear(); } else { MessageBox.Show("You should copy or move some line first."); } itemFound = true; break; } else if (item.suffix[0] == 'b') { if (copyRows.Count() != 0) { int numOfLines = copyRows.Count(); int counterH = 0; for (int i = counter + 1; i < (counter + numOfLines + 1); i++) { string myData = copyRows[(copyRows.Count() - numOfLines + counterH)].data; rows.Insert(i - 1, new Data { lineNum = counter + 1, data = myData, suffix = "=====" }); counterH++; } copyRows.Clear(); } else { MessageBox.Show("You should copy or move some line first."); } itemFound = true; break; } else if (item.suffix[0] == 'c') { if (item.suffix == "c") { copyRows.Add(rows[counter]); } else { int numOfLines = (int)Char.GetNumericValue(item.suffix[1]); for (int i = counter; i < (counter + numOfLines); i++) { copyRows.Add(rows[i]); } } itemFound = true; break; } else if (item.suffix[0] == 'm') { if (item.suffix == "m") { copyRows.Add(rows[counter]); rows.RemoveAt(counter); } else { int numOfLines = (int)Char.GetNumericValue(item.suffix[1]); for (int i = counter; i < (counter + numOfLines); i++) { copyRows.Add(rows[i]); } for (int j = counter; j < (counter + numOfLines); j++) { rows.RemoveAt(counter); } } itemFound = true; break; } else if (item.suffix[0] == '“' || item.suffix[0] == '"') { string myData = rows[counter].data; rows.Insert(counter + 1, new Data { lineNum = counter + 1, data = myData, suffix = "=====" }); itemFound = true; break; } counter++; } } } if (itemFound) { UpdateColumns(); Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.ApplicationIdle, new Action(ProcessRows)); } }
public static bool GetTextBoxController(DataGridCell element) { return((bool)element.GetValue(TextBoxControllerProperty)); }
private bool EndEdit(RoutedCommand command, DataGridCell cellContainer, DataGridEditingUnit editingUnit, bool exitEditMode) { bool cellLeftEditingMode = true; bool rowLeftEditingMode = true; if (cellContainer != null) { if (command.CanExecute(editingUnit, cellContainer)) { command.Execute(editingUnit, cellContainer); } cellLeftEditingMode = !cellContainer.IsEditing; rowLeftEditingMode = !IsEditingRowItem && !IsAddingNewItem; } if (!exitEditMode) { if (editingUnit == DataGridEditingUnit.Cell) { if (cellContainer != null) { if (cellLeftEditingMode) { return BeginEdit(null); } } else { // A cell was not placed in edit mode return false; } } else { if (rowLeftEditingMode) { object rowItem = cellContainer.RowDataItem; if (rowItem != null) { EditRowItem(rowItem); return IsEditingRowItem; } } // A row item was not placed in edit mode return false; } } return cellLeftEditingMode && ((editingUnit == DataGridEditingUnit.Cell) || rowLeftEditingMode); }
internal abstract FrameworkElement GenerateElement(object childData); //todo: the proper signature is: protected abstract FrameworkElement GenerateElement(object dataItem); internal virtual void EnterEditionMode(DataGridCell dataGridCell) { }
/// <summary> /// Notification that a particular cell's IsSelected property changed. /// </summary> internal void CellIsSelectedChanged(DataGridCell cell, bool isSelected) { if (!IsUpdatingSelectedCells) { DataGridCellInfo cellInfo = new DataGridCellInfo(cell); if (isSelected) { _selectedCells.AddValidatedCell(cellInfo); } else if (_selectedCells.Contains(cellInfo)) { _selectedCells.Remove(cellInfo); } } }
internal virtual void LeaveEditionMode(DataGridCell dataGridCell) { }
/// <summary> /// Creates the visual tree that will become the content of a cell. /// </summary> protected abstract FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem);
private void IDListView_SelectChange(object sender, SelectionChangedEventArgs e) { IDListItem item = (sender as ListView).SelectedItem as IDListItem; if (item == null) { return; } Excel excel = GlobalCfg.Instance.GetParsedExcel(_listItemChoosed.FilePath); List <PropertyInfo> propertyList = excel.Properties; ObservableCollection <PropertyListItem> fieldList = new ObservableCollection <PropertyListItem>(); _IDItemSelected = item; List <lparser.config> configs = GlobalCfg.Instance.GetTableRow(item.ID); string ename = string.Empty; for (int i = 0; i < propertyList.Count; i++) { ename = propertyList[i].ename; fieldList.Add(new PropertyListItem() { PropertyName = propertyList[i].cname, EnName = propertyList[i].ename, Context = configs[0] != null && configs[0].propertiesDic.ContainsKey(ename) ? configs[0].propertiesDic[ename].value : null, Trunk = configs[1] != null && configs[1].propertiesDic.ContainsKey(ename) ? configs[1].propertiesDic[ename].value : null, Studio = configs[2] != null && configs[2].propertiesDic.ContainsKey(ename) ? configs[2].propertiesDic[ename].value : null, TF = configs[3] != null && configs[3].propertiesDic.ContainsKey(ename) ? configs[3].propertiesDic[ename].value : null, Release = configs[4] != null && configs[4].propertiesDic.ContainsKey(ename) ? configs[4].propertiesDic[ename].value : null }); } propertyDataGrid.ItemsSource = fieldList; ResetGenBtnState(); //刷新单元格颜色 for (int j = 0; j < GlobalCfg.BranchCount; j++) { tablerowdiff trd = GlobalCfg.Instance.GetCellAllStatus(item.ID, j); if (trd == null) { continue; } for (int a = 0; a < fieldList.Count; a++) { if (trd.modifiedcells != null && trd.modifiedcells.ContainsKey(fieldList[a].EnName)) { DataGridCell dataGridCell = GetCell(propertyDataGrid, a, j + 3); dataGridCell.Background = Brushes.LightBlue; } if (trd.modifiedcells != null && trd.addedcells.ContainsKey(fieldList[a].EnName)) { DataGridCell dataGridCell = GetCell(propertyDataGrid, a, j + 3); dataGridCell.Background = Brushes.LightPink; } if (trd.modifiedcells != null && trd.deletedcells.ContainsKey(fieldList[a].EnName)) { DataGridCell dataGridCell = GetCell(propertyDataGrid, a, j + 3); dataGridCell.Background = Brushes.LightBlue; } } } }
/// <summary> /// When overridden in a derived class, gets an editing element that is bound to the column's <see cref="P:System.Windows.Controls.DataGridBoundColumn.Binding"/> property value. /// </summary> /// <param name="cell">The cell that will contain the generated element.</param> /// <param name="dataItem">The data item represented by the row that contains the intended cell.</param> /// <returns> /// A new editing element that is bound to the column's <see cref="P:System.Windows.Controls.DataGridBoundColumn.Binding"/> property value. /// </returns> protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) { DateTimePicker dtp = new DateTimePicker { Margin = new Thickness(4.0), VerticalAlignment = VerticalAlignment.Center, VerticalContentAlignment = VerticalAlignment.Center, DateTimeFormat = this.DateTimeFormat, DateTimeKind = this.DateTimeKind, Language = cell.Language }; if (!string.IsNullOrEmpty(Field)) { Binding selectedBinding = #if SILVERLIGHT new Binding(Field); #else new Binding("Attributes["+Field+"]"); if(FieldInfo != null && FieldInfo.Domain != null && FieldInfo.Domain is RangeDomain<DateTime>) { RangeDomainValidationRule rangeValidator = new RangeDomainValidationRule(); rangeValidator.MinValue = (FieldInfo.Domain as RangeDomain<DateTime>).MinimumValue; rangeValidator.MaxValue = (FieldInfo.Domain as RangeDomain<DateTime>).MaximumValue; rangeValidator.ValidationStep = ValidationStep.ConvertedProposedValue; selectedBinding.ValidationRules.Add(rangeValidator); } #endif selectedBinding.Mode = BindingMode.TwoWay; selectedBinding.ValidatesOnExceptions = true; selectedBinding.NotifyOnValidationError = true; dtp.SetBinding(DateTimePicker.SelectedDateProperty, selectedBinding); } return dtp; }
protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem) { var contentPresenter = new ContentPresenter(); Dispatcher.BeginInvoke((Action)(() => { if ((dataItem.GetType().GetProperty(this.BindingPath) != null)) { if (this.SupportedValues != null) { var comboBox = new ComboBox(); comboBox.IsHitTestVisible = false; var itemsSourceBinding = new Binding("SupportedValues") { Source = this }; comboBox.SetBinding(ComboBox.ItemsSourceProperty, itemsSourceBinding); comboBox.DisplayMemberPath = this.SupportedValuesDisplayMemberPath; comboBox.SelectedValuePath = this.SupportedValuesValuePath; comboBox.IsSynchronizedWithCurrentItem = false; comboBox.SetBinding(ComboBox.SelectedValueProperty, new Binding(this.BindingPath) { Source = dataItem, Mode = BindingMode.TwoWay }); contentPresenter.Content = comboBox; } else { string typeName = dataItem.GetType().GetProperty(this.BindingPath).PropertyType.FullName; switch (typeName) { case "System.Int32": case "System.Int64": case "System.String": { var textBlock = new TextBlock(); textBlock.SetBinding(TextBlock.TextProperty, new Binding(this.BindingPath) { Source = dataItem }); contentPresenter.Content = textBlock; break; } case "System.Boolean": { var checkBox = new CheckBox(); checkBox.SetBinding(CheckBox.IsCheckedProperty, new Binding(this.BindingPath) { Source = dataItem }); checkBox.IsEnabled = false; contentPresenter.Content = checkBox; break; } } } } })); return(contentPresenter); }
/// <summary> /// Creates the visual tree that will become the content of a cell. /// </summary> /// <param name="isEditing">Whether the editing version is being requested.</param> /// <param name="dataItem">The data item for the cell.</param> /// <param name="cell">The cell container that will receive the tree.</param> private FrameworkElement LoadTemplateContent(bool isEditing, object dataItem, DataGridCell cell) { DataTemplate template = ChooseCellTemplate(isEditing); DataTemplateSelector templateSelector = ChooseCellTemplateSelector(isEditing); if (template != null || templateSelector != null) { ContentPresenter contentPresenter = new ContentPresenter(); BindingOperations.SetBinding(contentPresenter, ContentPresenter.ContentProperty, new Binding()); contentPresenter.ContentTemplate = template; contentPresenter.ContentTemplateSelector = templateSelector; return contentPresenter; } return null; }
protected override IEnumerable <StatementExecutionModel> BuildExecutionModels(DataGridCell cell) { var customTypeAttributeValue = (CustomTypeAttributeValue)cell.DataContext; return(customTypeAttributeValue.ColumnHeader.ParentReferenceDataSources .Select(s => s.CreateExecutionModel(new [] { customTypeAttributeValue.Value }))); }
/// <summary> /// Creates the visual tree for text based cells. /// </summary> protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) { TextBox textBox = new TextBox(); SyncProperties(textBox); ApplyStyle(/* isEditing = */ true, /* defaultToElementStyle = */ false, textBox); ApplyBinding(textBox, TextBox.TextProperty); return textBox; }
protected override IReadOnlyCollection <IReferenceDataSource> GetReferenceDataSources(DataGridCell cell) { var customTypeAttributeValue = (CustomTypeAttributeValue)cell.DataContext; return(customTypeAttributeValue.ColumnHeader.ParentReferenceDataSources); }
public DataFieldWindow(string xpath) { InitializeComponent(); //strip_html.IsChecked = Settings.Default.StripHtml; //strip_html.Checked += delegate // { // Settings.Default.StripHtml = strip_html.IsChecked == true; // Settings.Default.Save(); // set_by_xpath(); // }; Ok.Click += delegate { if (string.IsNullOrWhiteSpace(Name.Text)) { Message.Exclaim("Name is not set!"); return; } DialogResult = true; Close(); }; Xpath.TextChanged += delegate { set_by_xpath(); }; //attributes.SelectionChanged += (o, e) => //{ // ((Item)Attributes.Items[Attributes.SelectedIndex]).Get = !((Item)Attributes.Items[Attributes.SelectedIndex]).Get; // this.Dispatcher. // e.Handled = true; // Attributes.UnselectAll(); //}; attributes.MouseLeftButtonUp += delegate(object sender, MouseButtonEventArgs e) { DataGridCell cell = null; DataGridRow row = null; for (DependencyObject d = (DependencyObject)e.OriginalSource; d != null; d = VisualTreeHelper.GetParent(d)) { if (cell == null) { cell = d as DataGridCell; } if (row == null) { row = d as DataGridRow; } if (cell != null && row != null) { break; } } if (cell == null || row == null) { return; } if (cell.Column.DisplayIndex == 0) { ((Item)row.Item).Get = !((Item)row.Item).Get; } //if (cell.Column.DisplayIndex == 3) //{ // Item i = ((Item)row.Item); // i.StripHtml = !i.StripHtml; // i.Value = i.StripHtml ? FieldPreparation.Html.Normalize(i.RawValue) : i.RawValue; //} attributes.Items.Refresh(); }; Xpath.Text = xpath; //attributes.CellEditEnding += delegate (object sender, DataGridCellEditEndingEventArgs e) //{ // if (e.EditAction == DataGridEditAction.Commit) // { // var column = e.Column as DataGridBoundColumn; // if (column != null) // { // var bindingPath = (column.Binding as Binding).Path.Path; // if (bindingPath == "Col2") // { // int rowIndex = e.Row.GetIndex(); // var el = e.EditingElement as TextBox; // // rowIndex has the row index // // bindingPath has the column's binding // // el.Text has the new, user-entered value // } // } // } //}; }
protected virtual IReadOnlyCollection <IReferenceDataSource> GetReferenceDataSources(DataGridCell cell) => _columnHeader.ParentReferenceDataSources;
/// <summary> /// Measures the children of a <see cref="T:System.Windows.Controls.Primitives.DataGridCellsPresenter"/> to /// prepare for arranging them during the <see cref="M:System.Windows.FrameworkElement.ArrangeOverride(System.Windows.Size)"/> pass. /// </summary> /// <param name="availableSize"> /// The available size that this element can give to child elements. Indicates an upper limit that child elements should not exceed. /// </param> /// <returns> /// The size that the <see cref="T:System.Windows.Controls.Primitives.DataGridCellsPresenter"/> determines it needs during layout, based on its calculations of child object allocated sizes. /// </returns> protected override Size MeasureOverride(Size availableSize) { if (this.OwningGrid == null) { return(base.MeasureOverride(availableSize)); } bool autoSizeHeight; double measureHeight; if (double.IsNaN(this.OwningGrid.RowHeight)) { // No explicit height values were set so we can autosize autoSizeHeight = true; measureHeight = double.PositiveInfinity; } else { this.DesiredHeight = this.OwningGrid.RowHeight; measureHeight = this.DesiredHeight; autoSizeHeight = false; } double frozenLeftEdge = 0; double totalDisplayWidth = 0; double scrollingLeftEdge = -this.OwningGrid.HorizontalOffset; this.OwningGrid.ColumnsInternal.EnsureVisibleEdgedColumnsWidth(); DataGridColumn lastVisibleColumn = this.OwningGrid.ColumnsInternal.LastVisibleColumn; foreach (DataGridColumn column in this.OwningGrid.ColumnsInternal.GetVisibleColumns()) { DataGridCell cell = this.OwningRow.Cells[column.Index]; // Measure the entire first row to make the horizontal scrollbar more accurate bool shouldDisplayCell = ShouldDisplayCell(column, frozenLeftEdge, scrollingLeftEdge) || this.OwningRow.Index == 0; EnsureCellDisplay(cell, shouldDisplayCell); if (shouldDisplayCell) { DataGridLength columnWidth = column.Width; bool autoGrowWidth = columnWidth.IsSizeToCells || columnWidth.IsAuto; if (column != lastVisibleColumn) { cell.EnsureGridLine(lastVisibleColumn); } // If we're not using star sizing or the current column can't be resized, // then just set the display width according to the column's desired width if (!this.OwningGrid.UsesStarSizing || (!column.ActualCanUserResize && !column.Width.IsStar)) { // In the edge-case where we're given infinite width and we have star columns, the // star columns grow to their predefined limit of 10,000 (or their MaxWidth) double newDisplayWidth = column.Width.IsStar ? Math.Min(column.ActualMaxWidth, DataGrid.DATAGRID_maximumStarColumnWidth) : Math.Max(column.ActualMinWidth, Math.Min(column.ActualMaxWidth, column.Width.DesiredValue)); column.SetWidthDisplayValue(newDisplayWidth); } // If we're auto-growing the column based on the cell content, we want to measure it at its maximum value if (autoGrowWidth) { cell.Measure(new Size(column.ActualMaxWidth, measureHeight)); this.OwningGrid.AutoSizeColumn(column, cell.DesiredSize.Width); column.ComputeLayoutRoundedWidth(totalDisplayWidth); } else if (!this.OwningGrid.UsesStarSizing) { column.ComputeLayoutRoundedWidth(scrollingLeftEdge); cell.Measure(new Size(column.LayoutRoundedWidth, measureHeight)); } // We need to track the largest height in order to auto-size if (autoSizeHeight) { this.DesiredHeight = Math.Max(this.DesiredHeight, cell.DesiredSize.Height); } } if (column.IsFrozen) { frozenLeftEdge += column.ActualWidth; } scrollingLeftEdge += column.ActualWidth; totalDisplayWidth += column.ActualWidth; } // If we're using star sizing (and we're not waiting for an auto-column to finish growing) // then we will resize all the columns to fit the available space. if (this.OwningGrid.UsesStarSizing && !this.OwningGrid.AutoSizingColumns) { double adjustment = this.OwningGrid.CellsWidth - totalDisplayWidth; totalDisplayWidth += adjustment - this.OwningGrid.AdjustColumnWidths(0, adjustment, false); // Since we didn't know the final widths of the columns until we resized, // we waited until now to measure each cell double leftEdge = 0; foreach (DataGridColumn column in this.OwningGrid.ColumnsInternal.GetVisibleColumns()) { DataGridCell cell = this.OwningRow.Cells[column.Index]; column.ComputeLayoutRoundedWidth(leftEdge); cell.Measure(new Size(column.LayoutRoundedWidth, measureHeight)); if (autoSizeHeight) { this.DesiredHeight = Math.Max(this.DesiredHeight, cell.DesiredSize.Height); } leftEdge += column.ActualWidth; } } // Measure FillerCell, we're doing it unconditionally here because we don't know if we'll need the filler // column and we don't want to cause another Measure if we do this.OwningRow.FillerCell.Measure(new Size(double.PositiveInfinity, this.DesiredHeight)); this.OwningGrid.ColumnsInternal.EnsureVisibleEdgedColumnsWidth(); return(new Size(this.OwningGrid.ColumnsInternal.VisibleEdgedColumnsWidth, this.DesiredHeight)); }
///-------------------------------------------------------------------------------- /// <summary>This method generates the element.</summary> ///-------------------------------------------------------------------------------- protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem) { Element = base.GenerateElement(cell, dataItem); CopyItemsSource(Element); return(Element); }
/// <summary> /// Raises the CancelEdit command. /// If a cell is currently in edit mode, cancels the cell edit, but leaves any row edits alone. /// </summary> /// <returns>true if the cell exits edit mode, false otherwise.</returns> internal bool CancelEdit(DataGridCell cell) { DataGridCell currentCell = CurrentCellContainer; if (currentCell != null && currentCell == cell && currentCell.IsEditing) { return CancelEdit(DataGridEditingUnit.Cell); } return true; }
/// <summary> /// Initializes a new instance of the <see cref="DataGridCellAutomationPeer"/> class. /// </summary> /// <param name="owner">DataGridCell</param> public DataGridCellAutomationPeer(DataGridCell owner) : base(owner) { }
private void UpdateRowEditing(DataGridCell cell) { object rowDataItem = cell.RowDataItem; // If the row is not in edit/add mode, then clear its IsEditing flag. if (!IsAddingOrEditingRowItem(rowDataItem)) { cell.RowOwner.IsEditing = false; _editingRowItem = null; _editingRowIndex = -1; } }
//--------------------------------------------------------------------- public FrameworkElement GenerateElementPublic( DataGridCell cell, object dataItem) { return(GenerateElement(cell, dataItem)); }
/// <summary> /// There was general input that means that selection should occur on /// the given cell. /// </summary> /// <param name="cell">The target cell.</param> /// <param name="startDragging">Whether the input also indicated that dragging should start.</param> internal void HandleSelectionForCellInput(DataGridCell cell, bool startDragging, bool allowsExtendSelect, bool allowsMinimalSelect) { DataGridSelectionUnit selectionUnit = SelectionUnit; // If the mode is None, then no selection will occur if (selectionUnit == DataGridSelectionUnit.FullRow) { // In FullRow mode, items are selected MakeFullRowSelection(cell.RowDataItem, allowsExtendSelect, allowsMinimalSelect); } else { // In the other modes, cells can be individually selected MakeCellSelection(new DataGridCellInfo(cell), allowsExtendSelect, allowsMinimalSelect); } if (startDragging) { BeginDragging(); } }
protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) { throw new NotImplementedException(); }
/// <summary> /// Creates the visual tree that will become the content of a cell. /// </summary> /// <param name="isEditing">Whether the editing version is being requested.</param> /// <param name="dataItem">The data item for the cell.</param> /// <param name="cell">The cell container that will receive the tree.</param> internal FrameworkElement BuildVisualTree(bool isEditing, object dataItem, DataGridCell cell) { if (isEditing) { return GenerateEditingElement(cell, dataItem); } else { return GenerateElement(cell, dataItem); } }
private void Grid_LostFocus(object sender, RoutedEventArgs e) { DataGridCell cell = null; if (e.OriginalSource.GetType() == typeof(CheckBox)) { cell = (DataGridCell)((CheckBox)e.OriginalSource).Parent; } else if (e.OriginalSource.GetType() == typeof(TextBox)) { cell = (DataGridCell)((TextBox)e.OriginalSource).Parent; } else if (e.OriginalSource.GetType() == typeof(DataGridCell)) { cell = (DataGridCell)e.OriginalSource; } if (cell == null) { return; } Style cellstyle = new Style(typeof(DataGridCell)); if (mDSTableDetails.DSTableType == DataSourceTable.eDSTableType.GingerKeyValue) { string keyName = ((DataRowView)cell.DataContext).Row["GINGER_KEY_NAME"].ToString(); if (cell.Column.Header.ToString() == "GINGER__KEY__NAME" && (keyName == "" || getKeyRows(keyName).Count() > 1)) { if (keyName == "") { cellstyle.Setters.Add(new Setter(DataGridRow.ToolTipProperty, "Empty Key Name")); } else { cellstyle.Setters.Add(new Setter(DataGridRow.ToolTipProperty, "Duplicate Key Name")); } cellstyle.Setters.Remove(SetterModified); cellstyle.Setters.Add(SetterError); cellstyle.Setters.Add(SetterBorderBold); cell.Style = cellstyle; return; } else if (((DataRowView)cell.DataContext).Row.RowError == "Duplicate Key Name") { DataRow[] foundRows; foundRows = mDSTableDetails.DataTable.Select("GINGER_KEY_NAME='" + keyName + "'"); if (foundRows.Count() < 2) { foreach (DataRow dr1 in foundRows) { dr1.RowError = ""; } } } } string colName = ""; if (cell.Column.Header != null) { colName = cell.Column.Header.ToString().Replace("__", "_"); } if (((DataRowView)cell.DataContext).Row.RowState == DataRowState.Added || ((DataRowView)cell.DataContext).Row[colName].ToString() != ((DataRowView)cell.DataContext).Row[colName, DataRowVersion.Original].ToString()) { ((DataRowView)cell.DataContext).Row.RowError = ""; cellstyle.Setters.Add(new Setter(DataGridRow.ToolTipProperty, "")); cellstyle.Setters.Add(SetterModified); cellstyle.Setters.Add(SetterBorderBold); } else { ((DataRowView)cell.DataContext).Row.RowError = ""; cellstyle.Setters.Add(new Setter(DataGridRow.ToolTipProperty, "")); cellstyle.Setters.Remove(SetterModified); cellstyle.Setters.Remove(SetterBorderBold); } cell.Style = cellstyle; }
protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem) { FrameworkElement element = base.GenerateElement(cell, dataItem); CopyItemsSource(element); return element; }
protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) { return(GenerateElement(cell, dataItem)); }
/// <summary> /// When overridden in a derived class, gets a read-only element that is bound to the column's <see cref="P:System.Windows.Controls.DataGridBoundColumn.Binding"/> property value. /// </summary> /// <param name="cell">The cell that will contain the generated element.</param> /// <param name="dataItem">The data item represented by the row that contains the intended cell.</param> /// <returns> /// A new, read-only element that is bound to the column's <see cref="P:System.Windows.Controls.DataGridBoundColumn.Binding"/> property value. /// </returns> protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem) { TextBlock block = new TextBlock() { Margin = new Thickness(4.0), VerticalAlignment = VerticalAlignment.Center }; if (!string.IsNullOrEmpty(Field) && this.CodedValueSources != null) { nameConverter.Field = this.Field; Binding binding = #if SILVERLIGHT new Binding(); #else new Binding("Attributes["+Field+"]"); #endif binding.Mode = BindingMode.OneWay; binding.Converter = nameConverter; binding.ConverterParameter = this.CodedValueSources; block.SetBinding(TextBlock.TextProperty, binding); } return block; }
// Here the datagrid itself is parsed because it is the datagrid cells that // need to be marked bad. // Returns true if there are issues. private bool ValidateRenamedList() { // OMG!! bool ThereAreIssues = false; bool ThereAreIllegals = false; int invalidCount = 0; int changedCount = 0; DataGrid dgr = dg_names; List <string> NotUniqueOnDiskList = new List <string>(); List <string> NotUniqueInThisList = new List <string>(); string basePath = LocfRenamer.PathPart; int numRows = LocfRenamer.TheFiles.Count(); for (int i = 0; i < numRows; i++) { DataGridRow thisRow = WPFDataGridHelpers.GetRow(dgr, i); DataGridCell CellCur = dgr.GetCell(thisRow, 0); DataGridCell CellRen = dgr.GetCell(thisRow, 1); // But the cell reads "" if it is not first updated when this validate method is called from // a textchanged event!!! CellRen.UpdateLayout(); if (CellRen != null) { // readonly cells are TextBlocks!! TextBlock tblkCur = CellCur.Content as TextBlock; // But when not editing a textblock?? //TextBox tbxRen = CellRen.Content as TextBox; TextBlock tblkRen = CellRen.Content as TextBlock; if (tblkRen != null) { string name_grid_cell_Fnew = tblkRen.Text; string name_grid_cell_Fcur = tblkCur.Text; string msg = string.Empty; string fullPath = basePath + name_grid_cell_Fnew; if (!Helpers.IsValidWindowsFileName(name_grid_cell_Fnew)) { // invalid characters Dispatcher.BeginInvoke((Action)(() => CellRen.Foreground = Brushes.Red)); ThereAreIssues = true; ThereAreIllegals = true; invalidCount++; continue; } else { if (!name_grid_cell_Fcur.Equals(name_grid_cell_Fnew, StringComparison.CurrentCultureIgnoreCase)) { // new tlbk <> cur tlbk There is a change, no matter what. changedCount++; Dispatcher.BeginInvoke((Action)(() => CellRen.Foreground = Brushes.DarkGreen)); // innocent until proven guilty if (!Helpers.MarkDataGridCellForFile(CellRen, fullPath, false)) { // There is another file on disk like this one. NotUniqueOnDiskList.Add(name_grid_cell_Fnew); Dispatcher.BeginInvoke((Action)(() => CellRen.Foreground = Brushes.Red)); ThereAreIssues = true; invalidCount++; } else { // No file issue, now look for duplicates in the bound list. // We are comparing this row to all entries // in the bound list looking for the same name used for other current names. foreach (RenamerFileName list_rfn in LocfRenamer.TheFiles) { if (list_rfn.Present_Name.Equals(name_grid_cell_Fcur, StringComparison.CurrentCultureIgnoreCase)) { // This must be the same name. Do nothing. Go on to the next. continue; // We do not want to do any more comparisons. } if (list_rfn.Changed_Name.Equals(name_grid_cell_Fnew, StringComparison.CurrentCultureIgnoreCase)) { // list changed = a new changed, must be a name already used. // In this code the same name can wind up multiple times in the list if this // is not checked first. if (!NotUniqueInThisList.Contains(name_grid_cell_Fnew)) { NotUniqueInThisList.Add(name_grid_cell_Fnew); } // this item has an issue ThereAreIssues = true; Dispatcher.BeginInvoke((Action)(() => CellRen.Foreground = Brushes.Red)); invalidCount++; // When the name is a duplicate within the list, the prior duplicates will have // been marked green as valid ne ones. We need to pass through the list again to remark it to red for (int j = 0; j < numRows; j++) { DataGridRow thisReRow = WPFDataGridHelpers.GetRow(dgr, j); DataGridCell CellReRen = dgr.GetCell(thisReRow, 1); TextBlock retblkRen = CellReRen.Content as TextBlock; if (retblkRen.Text.Equals(name_grid_cell_Fnew)) { Dispatcher.BeginInvoke((Action)(() => CellReRen.Foreground = Brushes.Red)); } } } } } } else // no change at all { // item not changed Dispatcher.BeginInvoke((Action)(() => CellRen.Foreground = Brushes.Black)); } } //// If after the change the two wind up being equal, like in the case of a reset, then make it black. //if (name_grid_cell_Fcur.Equals(name_grid_cell_Fcur)) //{ // Dispatcher.BeginInvoke((Action)(() => CellRen.Foreground = Brushes.Black)); //} } } } if (ThereAreIssues) { string msgDetail = string.Empty; string moreDetail = string.Empty; if (ThereAreIllegals) { msgDetail = "There are illegal characters."; } if (NotUniqueOnDiskList.Count > 0) { moreDetail = "There are existing files elsewhere: " + string.Join(" , ", NotUniqueOnDiskList); if (ThereAreIllegals) { msgDetail = msgDetail + " , " + moreDetail; } else { msgDetail = moreDetail; } } if (NotUniqueInThisList.Count > 0) { moreDetail = "These are duplicates names: " + string.Join(" , ", NotUniqueInThisList); if (ThereAreIllegals || NotUniqueOnDiskList.Count > 0) { msgDetail = msgDetail + " , " + moreDetail; } else { msgDetail = moreDetail; } } Dispatcher.BeginInvoke((Action)(() => { Lb_topmsg.Content = "There are naming issues."; Lb_topmsg.Foreground = Brushes.Red; TBLK_msg.Text = msgDetail; TBLK_msg.Visibility = Visibility.Visible; TBLK_msg.Foreground = Brushes.Red; })); } else { Dispatcher.BeginInvoke((Action)(() => { Lb_topmsg.Content = string.Empty; Lb_topmsg.Foreground = Brushes.Black; TBLK_msg.Text = string.Empty; TBLK_msg.Foreground = Brushes.Black; TBLK_msg.Visibility = Visibility.Collapsed; })); } Dispatcher.BeginInvoke((Action)(() => { But_rename.IsEnabled = (changedCount > invalidCount); })); return(ThereAreIssues); }
/// <summary> /// When overridden in a derived class, gets a read-only element that is bound to the column's <see cref="P:System.Windows.Controls.DataGridBoundColumn.Binding"/> property value. /// </summary> /// <param name="cell">The cell that will contain the generated element.</param> /// <param name="dataItem">The data item represented by the row that contains the intended cell.</param> /// <returns> /// A new, read-only element that is bound to the column's <see cref="P:System.Windows.Controls.DataGridBoundColumn.Binding"/> property value. /// </returns> protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem) { TextBlock block = new TextBlock { Margin = new Thickness(4.0), VerticalAlignment = VerticalAlignment.Center }; if (!string.IsNullOrEmpty(Field)) { converter.DateTimeFormat = this.DateTimeFormat; converter.DateTimeKind = this.DateTimeKind; Binding binding = #if SILVERLIGHT new Binding(Field); #else new Binding("Attributes["+Field+"]"); #endif binding.Mode = BindingMode.OneWay; binding.Converter = converter; block.SetBinding(TextBlock.TextProperty, binding); } return block; }
private void DataGrid_CellPointerPressed(object sender, DataGridCellPointerPressedEventArgs e) { Cell = e.Cell; Column = e.Column as DataGridPropertyTextColumn; }
/// <summary> /// When overridden in a derived class, gets a read-only element that is bound to the column's <see cref="P:System.Windows.Controls.DataGridBoundColumn.Binding"/> property value. /// </summary> /// <param name="cell">The cell that will contain the generated element.</param> /// <param name="dataItem">The data item represented by the row that contains the intended cell.</param> /// <returns> /// A new, read-only element that is bound to the column's <see cref="P:System.Windows.Controls.DataGridBoundColumn.Binding"/> property value. /// </returns> protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem) { TextBlock block = new TextBlock { Margin = new Thickness(4.0), VerticalAlignment = VerticalAlignment.Center }; if (!string.IsNullOrEmpty(Field)) { var codedValueSources = Utilities.DynamicCodedValueSource.GetCodedValueSources(LookupField, FieldInfo, dataItem, DynamicCodedValueSource, nullableSources); if (codedValueSources != null) { if (!string.IsNullOrEmpty(LookupField) && DynamicCodedValueSource != null) { nameConverter.LookupField = this.LookupField; nameConverter.Field = this.Field; Binding binding = #if SILVERLIGHT new Binding(); #else new Binding("Attributes["+Field+"]"); #endif binding.Mode = BindingMode.OneWay; binding.Converter = nameConverter; binding.ConverterParameter = #if SILVERLIGHT DynamicCodedValueSource; #else new Object[] { DynamicCodedValueSource, block }; #endif block.SetBinding(TextBlock.TextProperty, binding); } } else if (FieldInfo.Type == Client.Field.FieldType.Date) { if (!string.IsNullOrEmpty(Field)) { dateTimeConverter.DateTimeFormat = this.DateTimeFormat; dateTimeConverter.DateTimeKind = this.DateTimeKind; Binding binding = #if SILVERLIGHT new Binding(Field); #else new Binding("Attributes["+Field+"]"); #endif binding.Mode = BindingMode.OneWay; binding.Converter = dateTimeConverter; block.SetBinding(TextBlock.TextProperty, binding); } } else { Binding binding = #if SILVERLIGHT new Binding(Field); #else new Binding("Attributes["+Field+"]"); #endif binding.Mode = BindingMode.OneWay; block.SetBinding(TextBlock.TextProperty, binding); } } return block; }
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { SolidColorBrush newColor = new SolidColorBrush(Color.FromArgb(255, 250, 250, 250)); //NewColor = null; DataGridCell cell = null; DataRow row = null; string columnName = null; DataColumn column = null; Type cellType = null; if (values[1] is DataRow) { cell = (DataGridCell)values[0]; cell.ToolTip = null; cell.BorderBrush = null; cell.BorderThickness = new Thickness(0); row = (DataRow)values[1]; // Skip deleted rows, since they disappear. if (row.RowState == DataRowState.Deleted || row.RowState == DataRowState.Detached) { return(newColor); } columnName = (string)cell.Column.Header; column = row.Table.Columns[columnName]; cellType = row[columnName].GetType(); } else { //throw new ArgumentException("BackgroundConverter not given DataRow"); return(newColor); } if (column.ReadOnly) { newColor = new SolidColorBrush(Color.FromArgb(255, 210, 210, 210)); } if (IsKeyColumn(row.Table, columnName)) { newColor = new SolidColorBrush(Colors.LightGoldenrodYellow); } if (row.RowState == DataRowState.Modified && !row[column, DataRowVersion.Current].Equals(row[column, DataRowVersion.Original])) { newColor = new SolidColorBrush(Colors.LightPink); cell.ToolTip = String.Format("Original Value: {0}", row[column, DataRowVersion.Original]); } if (column.ExtendedProperties.ContainsKey("Hidden") && (bool)column.ExtendedProperties["Hidden"]) { newColor = new SolidColorBrush(Colors.LightSteelBlue); } if (row.RowState == DataRowState.Added) { newColor = new SolidColorBrush(Colors.LightGreen); } if (row.HasErrors) { if (row.GetColumnsInError().Contains(column)) { newColor = new SolidColorBrush(Color.FromArgb(255, 250, 250, 250)); cell.BorderBrush = new SolidColorBrush(Colors.Red); cell.BorderThickness = new Thickness(5); cell.ToolTip = String.Format("{0}\nOriginal Value: {1}", row.GetColumnError(column), row.RowState == DataRowState.Added ? "None, new row." : row[column, DataRowVersion.Original]); } } return(newColor); }
/// <summary> /// Creates the visual tree that will become the content of a cell. /// </summary> protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) { return LoadTemplateContent(/* isEditing = */ true, dataItem, cell); }
protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem) { var value = property.GetValue(dataItem); return(new LiteTextBlock(new Size(100, 20), value != null ? value.ToString() : string.Empty, this.glyphTypeface, 10)); }
/// <summary> /// 表格获取值 /// </summary> public void getTableData() { string sql = ""; DataSet ds = new DataSet(); string str = TBID.Text; string[] sArrayID = Regex.Split(str, "\r\n", RegexOptions.IgnoreCase); string starTime = TBStartTime.Text; string endTime = TBEndTime.Text; int num = int.Parse(TBReturnNum.Text); bool IsExist = false; str = BaseClass.getSqlValue(sArrayID); sql = "select top " + num + " * from T_Weight as t1 " + "join T_Staff as t2 on t2.name_staff = t1.Weight_WorkderId " + "join T_Region as t3 on t3.Region_Id = t2.Region_staff " + "where t1.Weight_Type is not null " + "and t1.Weight_WorkderId = '" + staff_name + "'"; if (TBPlant != null && TBPlant.Text != "") { string plant = TBPlant.Text; sql += " and t3.Region_Id = '" + plant + "' "; } if (TBName != null && TBName.Text != "") { string name = TBName.Text; sql += " and t1.Weight_UserName = '******' "; } if (TBScan != null && TBScan.Text != "") { string scan = TBScan.Text; sql += " and t1.Weight_WorkderId = '" + scan + "' "; } string type = TBType.Text; if (CBID.IsChecked == true) { sql += "and t1.Weight_ConID in " + str + " "; } else { sql += "and t1.Weight_Time between '" + starTime + "' and '" + endTime + "'"; } ds = DBClass.execQuery(sql); WeightList = new List <WeightModel>(); if (ds.Tables[0].Rows.Count > 0) { for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { string Weight_Type = ""; SolidColorBrush WeightColor = Brushes.Black; if (ds.Tables[0].Rows[i]["Weight_Type"].ToString() == "N") { Weight_Type = "已到件"; } if (double.Parse(ds.Tables[0].Rows[i]["Weight_Helf"].ToString()) > double.Parse(ds.Tables[0].Rows[i]["Weight_Weitgh"].ToString())) { WeightColor = Brushes.Red; } WeightList.Add(new WeightModel() { Checking = false, Id = ds.Tables[0].Rows[i]["Id"].ToString(), Weight_ConID = ds.Tables[0].Rows[i]["Weight_ConID"].ToString(), Weight_Type = Weight_Type, Weight_Last = ds.Tables[0].Rows[i]["Weight_Last"].ToString(), Weight_WorkderId = ds.Tables[0].Rows[i]["Weight_WorkderId"].ToString(), Weight_Time = ds.Tables[0].Rows[i]["Weight_Time"].ToString(), Weight_Helf = ds.Tables[0].Rows[i]["Weight_Helf"].ToString(), Weight_Num = ds.Tables[0].Rows[i]["Weight_Num"].ToString(), Weight_Shelf = ds.Tables[0].Rows[i]["Weight_Shelf"].ToString(), Weight_Note = ds.Tables[0].Rows[i]["Weight_Note"].ToString(), Weight_UserId = ds.Tables[0].Rows[i]["Weight_UserId"].ToString(), Weight_UserName = ds.Tables[0].Rows[i]["Weight_UserName"].ToString(), Weight_Weitgh = ds.Tables[0].Rows[i]["Weight_Weitgh"].ToString(), Weight_Pack = ds.Tables[0].Rows[i]["Weight_Pack"].ToString(), Weight_Region = ds.Tables[0].Rows[i]["Weight_Region"].ToString(), Weight_NoteStaff = ds.Tables[0].Rows[i]["Weight_NoteStaff"].ToString(), Weight_ConTranId = ds.Tables[0].Rows[i]["Weight_ConTranId"].ToString(), Weight_OverLong = ds.Tables[0].Rows[i]["Weight_OverLong"].ToString(), Weight_OverHelf = ds.Tables[0].Rows[i]["Weight_OverHelf"].ToString(), WeightColor = WeightColor }); } } str = ""; for (int i = 0; i < sArrayID.Length; i++) { IsExist = false; for (int j = 0; j < ds.Tables[0].Rows.Count; j++) { if (sArrayID[i].Trim().Equals(ds.Tables[0].Rows[j]["Weight_ConID"])) { IsExist = true; } } if (IsExist == false) { str += sArrayID[i].Trim() + "\r\n"; } } this.NoID.Text = str; this.DG1.CanUserAddRows = false; this.DG1.ItemsSource = WeightList; //创建数据源、绑定数据源 if (!Window.GetWindow(DG1).IsVisible) { Window.GetWindow(DG1).Show(); } DG1.UpdateLayout(); for (int i = 0; i < this.DG1.Items.Count; i++) { DataGridRow row = (DataGridRow)this.DG1.ItemContainerGenerator.ContainerFromIndex(i); DataGridCellsPresenter presenter = BaseClass.GetVisualChild <DataGridCellsPresenter>(row); DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(3); string strCell = ""; TextBlock tbStr = (TextBlock)cell.Content; strCell = tbStr.Text.ToString(); switch (strCell) { case "已到件": row.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FF9FF59F")); break; } } }
private static void EnsureCellDisplay(DataGridCell cell, bool displayColumn) { if (cell.IsCurrent) { if (displayColumn) { cell.Visibility = Visibility.Visible; cell.Clip = null; } else { // Clip RectangleGeometry rg = new RectangleGeometry(); rg.Rect = Rect.Empty; cell.Clip = rg; } } else { cell.Visibility = displayColumn ? Visibility.Visible : Visibility.Collapsed; } }
void Window1_MouseRightButtonUp(object sender, MouseButtonEventArgs e) { DependencyObject dep = (DependencyObject)e.OriginalSource; while ((dep != null) && !(dep is DataGridCell)) { dep = VisualTreeHelper.GetParent(dep); } if (dep == null) { return; } if (dep is DataGridCell) { DataGridCell cell = dep as DataGridCell; cell.Focus(); while ((dep != null) && !(dep is DataGridRow)) { dep = VisualTreeHelper.GetParent(dep); } DataGridRow row = dep as DataGridRow; dataRoom.SelectedItem = row.DataContext; Model.view.RoomView RowData = (Model.view.RoomView)dataRoom.SelectedItem; DisRoom.Header = RowData.STATUS == "Disabled" ? "Active" : "Disable Room"; switch (RowData.STATUS) { case "In Use": CusInfo.IsEnabled = true; DisRoom.IsEnabled = false; Booking_MenuItem.IsEnabled = false; Order_MenuItem.IsEnabled = true; Edit_MenuItem.IsEnabled = false; Checkbill_MenuItem.IsEnabled = true; Checkin_MenuItem.IsEnabled = true; break; case "Booked": CusInfo.IsEnabled = true; DisRoom.IsEnabled = false; Booking_MenuItem.IsEnabled = false; Order_MenuItem.IsEnabled = false; Edit_MenuItem.IsEnabled = false; Checkbill_MenuItem.IsEnabled = false; Checkin_MenuItem.IsEnabled = true; break; case "Disabled": CusInfo.IsEnabled = false; DisRoom.IsEnabled = true; Booking_MenuItem.IsEnabled = false; Order_MenuItem.IsEnabled = false; Edit_MenuItem.IsEnabled = false; Checkbill_MenuItem.IsEnabled = false; Checkin_MenuItem.IsEnabled = false; break; case "Empty": CusInfo.IsEnabled = false; DisRoom.IsEnabled = true; Booking_MenuItem.IsEnabled = true; Order_MenuItem.IsEnabled = false; Edit_MenuItem.IsEnabled = true; Checkbill_MenuItem.IsEnabled = false; Checkin_MenuItem.IsEnabled = true; break; } if (accounttype == "Employee") { DisRoom.IsEnabled = false; Edit_MenuItem.IsEnabled = false; } } }
protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) { return(GenerateNumericUpDown(true, cell)); }