private static void IsValidChangedCallback(DependencyObject obj, DependencyPropertyChangedEventArgs e) { if (!GetIsEnabled(obj)) { throw new InvalidOperationException("The IsValid attached property can only be used when the IsEnabled " + "attached property is set to true."); } Binding binding = BindingOperations.GetBinding(obj, IsValidProperty); if (binding != null) { CheckBindingMode(binding.Mode); return; } MultiBinding multiBinding = BindingOperations.GetMultiBinding(obj, IsValidProperty); if (multiBinding != null) { CheckBindingMode(multiBinding.Mode); return; } PriorityBinding priorityBinding = BindingOperations.GetPriorityBinding(obj, IsValidProperty); if (priorityBinding != null) { throw new InvalidOperationException("PriorityBinding is not supported for the IsValid attached dependency property!"); } }
/// <summary> /// Метод, който визуализира цвета при неправилно въведени данни /// </summary> private void BeginInvalidInputAnimation() { ColorAnimation animation = new ColorAnimation(this.AnimationBrushColor, TimeSpan.FromSeconds(0.1)) { AutoReverse = true, FillBehavior = FillBehavior.Stop, DecelerationRatio = 0.8 }; // Ако свойството за Background участва в Binding, няма да може да бъде анимирано, затова временно // откачаме Binding-а и го възстановяваме след края на анимацията (в метода storyBoard_Completed()) if (BindingOperations.IsDataBound(this.AssociatedTextBox, Control.BackgroundProperty)) { this.animatedPropertyBinding = BindingOperations.GetBinding(this.AssociatedTextBox, Control.BackgroundProperty); this.animatedPropertyMultiBinding = BindingOperations.GetMultiBinding(this.AssociatedTextBox, Control.BackgroundProperty); if (this.animatedPropertyBinding != null || this.animatedPropertyMultiBinding != null) { // задаваме текущата стойност локално Brush currentValue = this.AssociatedObject.GetValue(Control.BackgroundProperty) as Brush; this.AssociatedTextBox.Background = currentValue; } } Storyboard.SetTargetProperty(animation, new PropertyPath("(Control.Background).(SolidColorBrush.Color)")); Storyboard storyBoard = new Storyboard(); storyBoard.Children.Add(animation); storyBoard.Completed += new EventHandler(StoryBoard_Completed); storyBoard.Begin(this.AssociatedTextBox); SystemSounds.Beep.Play(); }
private bool IsQualifiedForDeferrer(DeferredElement element) { var binding = BindingOperations.GetBinding(element.Element, element.DeferredProperty); var multiBinding = BindingOperations.GetMultiBinding(element.Element, element.DeferredProperty); return(null != binding && !DisallowedBindings.Contains(binding.Mode) || (null != multiBinding && !DisallowedBindings.Contains(multiBinding.Mode))); }
private bool HasQualifiedBinding(TextBox element) { var binding = BindingOperations.GetBinding(element, TextBox.TextProperty); var multiBinding = BindingOperations.GetMultiBinding(element, TextBox.TextProperty); return (null != binding && !DisallowedBindings.Contains(binding.Mode) || (null != multiBinding && !DisallowedBindings.Contains(multiBinding.Mode))); }
private async void btnSaveTxt2Bin_Click(object sender, RoutedEventArgs e) { // Выключим кнопку записи в файл чтобы сто раз не жмакали // так как у нас включен биндинг, нужно его засейвить потом ресторить. var btn = ((Button)sender); BindingBase binding = null; if (BindingOperations.IsDataBound(btn, IsEnabledProperty)) { binding = BindingOperations.GetBinding(btn, IsEnabledProperty) ?? (BindingBase)BindingOperations.GetMultiBinding(btn, IsEnabledProperty); } btn.IsEnabled = false; // Читаем ввод пользователя. Валидация ввода провдится еще в фазе ввода в форму. var binPrefix = tbxBinPrefix.Text; var filePath = tbxTxtPath.Text; // Инициализируем прогресс бар prgbTxt2Bin.IsIndeterminate = true; // прогрессор, будет апдейтить прогрессбар и строку статуса var progress = new Progress <ProgressReport>(report => { var str = ""; if (report.Finished) { str = "Обработано: {0} Затрачено: {1}".Put(report.ProcessedCount, report.TimeUsed); } else { str = "Обработано: {0} Текущий: {1} Затрачено: {2}".Put(report.ProcessedCount, report.Date.Date.ToShortDateString(), report.TimeUsed); } lblBarProcessStatus.Content = str; }); // заводим асинхронно конвертацию, если будут ошибки, они хэндлятся штатным образом. try { await Common.TxtToBinTradesAsync(filePath, binPrefix, progress); } catch (Exception ex) { Trace.Fail(ex.ToString()); lblBarProcessStatus.Content = "Error: {0}".Put(ex.Message); this.UpdateLayout(); } // восстановим биндинг кнопки, сбросим прогрессбар btn.SetBinding(IsEnabledProperty, binding); prgbTxt2Bin.IsIndeterminate = false; prgbTxt2Bin.Value = 0; }
private async void btnSaveBin2Txt_Click(object sender, RoutedEventArgs e) { // Получим выбранный тикер, если ничего не выбрали то выходим. var tickerInfo = cbxTickers.SelectedItem as BarsTickerInfo; if (tickerInfo == null) { return; } var timeframe = cbxTimeframe.SelectedItem as Interval; var decimals = int.Parse(tbxDecimals.Text); // Выключим кнопку записи в файл чтобы сто раз не жмакали // так как у нас включен биндинг, нужно его засейвить потом ресторить. var btn = ((Button)sender); BindingBase binding = null; if (BindingOperations.IsDataBound(btn, IsEnabledProperty)) { binding = BindingOperations.GetBinding(btn, IsEnabledProperty) ?? (BindingBase)BindingOperations.GetMultiBinding(btn, IsEnabledProperty); } btn.IsEnabled = false; // Инициализируем прогресс бар с учетом выбранного диапазона prgbBin2Txt.IsIndeterminate = true; // прогрессор, будет апдейтить прогрессбар и строку статуса var progress = new Progress <ProgressReport>(report => { prgbBin2Txt.Value = (int)report.Percent; lblTickProcessStatus.Content = "Обработано: {0} Затрачено: {1}".Put(report.ProcessedCount, report.TimeUsed); }); // заводим асинхронно конвертацию, если будут ошибки, они хэндлятся штатным образом. try { await Common.BinToTxtBarsAsync(tickerInfo, timeframe, decimals, progress); } catch (Exception ex) { Trace.Fail(ex.ToString()); lblTickProcessStatus.Content = "Error: {0}".Put(ex.Message); this.UpdateLayout(); } // вернем назад бинды и прогресс бар btn.SetBinding(IsEnabledProperty, binding); prgbBin2Txt.Value = 0; prgbBin2Txt.IsIndeterminate = false; this.UpdateLayout(); }
private void Cell_SourceUpdated(object sender, DataTransferEventArgs e) { _ = new TextBox(); TextBox TextSender = (TextBox)sender; new MultiBinding(); MultiBinding MultiBindText = BindingOperations.GetMultiBinding(TextSender, TextBox.TextProperty); new Binding(); Binding Bind0 = (Binding)MultiBindText.Bindings[0]; int rowText = Grid.GetRow(TextSender); new RowPuzzle(rowText); RowPuzzle SourceBindR = (RowPuzzle)Bind0.Source; if (SourceBindR.ParentGrid.Win()) { SourceBindR.ParentGrid.OnWinTrigger(); } }
public FormeWrapper Convertir([NotNull] MeshElement3D mesh) => (FormeWrapper)BindingOperations.GetMultiBinding(mesh, ModelVisual3D.TransformProperty)?.Bindings?.OfType <Binding>()?.First()?.Source;
/// <summary> /// Updates the binding on the property described by <paramref name="path"/> to use <paramref name="dataContext"/> as source. /// </summary> /// <param name="obj">The root object.</param> /// <param name="dataContext">The object to use as source.</param> /// <param name="path">A list of objects describing the path through the object tree to the property.</param> private bool UpdateBindingSource(object obj, object dataContext, ICollection <PathInfo> path) { object nestedObj = obj; bool hasNewlyDiscoveredObjects = false; var segmentsToTraverse = path.Take(path.Count - 1) .SkipWhile(p => p.Reference != null) .ToArray(); if (segmentsToTraverse.Length > 0) { // update object with last known reference var index = path.Count - segmentsToTraverse.Length - 1 - 1; if (index >= 0) { nestedObj = path.ElementAt(index) .Reference; } foreach (var pathSegment in segmentsToTraverse) { nestedObj = GetValueOf(nestedObj, pathSegment); pathSegment.Reference = nestedObj; hasNewlyDiscoveredObjects = true; } } else { // update object with last known reference nestedObj = path.ElementAt(path.Count - 2) .Reference; } var type = nestedObj.GetType(); var visual = nestedObj as DependencyObject; if (visual != null) { var secondLastSegment = path.ElementAt(path.Count - 2); if (secondLastSegment.PublicDependencyProperties == null) { secondLastSegment.PublicDependencyProperties = type.GetPublicStaticFields().ToArray(); } var lastSegmentName = path.Last().Name; foreach (var fi in secondLastSegment.PublicDependencyProperties) { var dp = fi.GetValue(null) as DependencyProperty; if (dp != null && dp.Name == lastSegmentName) { var binding = BindingOperations.GetBinding(visual, dp); if (binding != null && binding.Source == null) { BindingOperations.ClearBinding(visual, dp); var b = binding.Clone(); b.Source = dataContext; BindingOperations.SetBinding(visual, dp, b); break; } var multiBinding = BindingOperations.GetMultiBinding(visual, dp); if (multiBinding != null) { var newMultiBinding = multiBinding.Clone(); for (int a = 0; a < multiBinding.Bindings.Count; a++) { var innerBinding = multiBinding.Bindings[a] as Binding; if (innerBinding != null && innerBinding.Source == null) { var newInnerBinding = innerBinding.Clone(); newInnerBinding.Source = dataContext; newMultiBinding.Bindings.Add(newInnerBinding); } else { newMultiBinding.Bindings.Add(multiBinding.Bindings[a]); } } BindingOperations.ClearBinding(visual, dp); BindingOperations.SetBinding(visual, dp, newMultiBinding); } } } } return(hasNewlyDiscoveredObjects); }
private bool TryGetInitialValue(DependencyObject depo, DependencyProperty dp, ref object value) { if (depo == null || dp == null) { return(false); } Binding b = BindingOperations.GetBinding(depo, dp); if (b == null) { MultiBinding mb = BindingOperations.GetMultiBinding(depo, dp); if (mb == null) { return(false); } b = mb.Bindings[0] as Binding; } if (b == null || b.Path == null || string.IsNullOrEmpty(b.Path.Path)) { return(false); } BindingExpression be = BindingOperations.GetBindingExpression(depo, dp); if (be == null) { MultiBindingExpression mbe = BindingOperations.GetMultiBindingExpression(depo, dp); if (mbe == null) { return(false); } be = mbe.BindingExpressions[0] as BindingExpression; } if (be == null || be.DataItem == null) { return(false); } var dobj = be.DataItem as DataObj; if (dobj != null) { string prop = b.Path.Path.Replace("Model.", ""); if (initialModel != null) { var pi = initialModel.GetType().GetProperty(prop); if (pi != null) { value = pi.GetValue(initialModel, null); return(true); } } } return(TryGetInitialValue(be.DataItem as DependencyObject, DispatcherHelper.GetDependencyProperty(be.DataItem.GetType(), b.Path.Path + "Property"), ref value)); }
private async void btnSaveBin2Txt_Click(object sender, RoutedEventArgs e) { // Получим выбранный тикер, если ничего не выбрали то выходим. var tickerInfo = cbxTickers.SelectedItem as TradesTickerInfo; if (tickerInfo == null) { return; } // если границы не заданы, то диапазона не будет, будем брать все. DateRange dateRange; if (dpFrom.SelectedDate == null || dpTo.SelectedDate == null) { dateRange = null; } else { var from = (DateTime)dpFrom.SelectedDate; var to = (DateTime)dpTo.SelectedDate; if (from > to) { MessageBox.Show("Дата От должна быть всегда не больше даты До.", "Ошибка!", MessageBoxButton.OK, MessageBoxImage.Error); return; } dateRange = new DateRange(from, to); } // Выключим кнопку записи в файл чтобы сто раз не жмакали // так как у нас включен биндинг, нужно его засейвить потом ресторить. var btn = ((Button)sender); BindingBase binding = null; if (BindingOperations.IsDataBound(btn, IsEnabledProperty)) { binding = BindingOperations.GetBinding(btn, IsEnabledProperty) ?? (BindingBase)BindingOperations.GetMultiBinding(btn, IsEnabledProperty); } btn.IsEnabled = false; // Инициализируем прогресс бар с учетом выбранного диапазона prgbBin2Txt.Minimum = 0; prgbBin2Txt.Maximum = 100; prgbBin2Txt.Value = 0; // прогрессор, будет апдейтить прогрессбар и строку статуса var progress = new Progress <ProgressReport>(report => { prgbBin2Txt.Value = (int)report.Percent; lblTickProcessStatus.Content = "Обработано: {0} Затрачено: {1}".Put(report.ProcessedCount, report.TimeUsed); }); // заводим асинхронно конвертацию, если будут ошибки, они хэндлятся штатным образом. try { await Common.BinToTxtTradesAsync(tickerInfo, dateRange, progress); } catch (Exception ex) { Trace.Fail(ex.ToString()); lblTickProcessStatus.Content = "Error: {0}".Put(ex.Message); this.UpdateLayout(); } // восстановим биндинг кнопки, сбросим прогрессбар btn.SetBinding(IsEnabledProperty, binding); prgbBin2Txt.Value = 0; this.UpdateLayout(); }
public static bool CheckAllValidationErrors(DependencyObject dependencyObject, DependencyProperty dependencyProperty) { bool isValid = true; if (BindingOperations.IsDataBound(dependencyObject, dependencyProperty)) { Binding binding = BindingOperations.GetBinding(dependencyObject, dependencyProperty); MultiBinding multiBinding = null; if (binding == null) { multiBinding = BindingOperations.GetMultiBinding(dependencyObject, dependencyProperty); if (multiBinding == null) { return(true); } } if (binding != null && binding.ValidationRules.Count > 0 || multiBinding != null && multiBinding.ValidationRules.Count > 0) { BindingExpression bindingExpression = BindingOperations.GetBindingExpression(dependencyObject, dependencyProperty); MultiBindingExpression multiBindingExpression = null; if (bindingExpression == null) { multiBindingExpression = BindingOperations.GetMultiBindingExpression(dependencyObject, dependencyProperty); if (multiBindingExpression == null) { return(true); } } BindingExpressionBase expression = bindingExpression ?? (BindingExpressionBase)multiBindingExpression; switch (binding != null ? binding.Mode : multiBinding.Mode) { case BindingMode.OneTime: case BindingMode.OneWay: expression.UpdateTarget(); break; default: expression.UpdateSource(); break; } if (expression.HasError) { isValid = false; } } // Another method: foreach (ValidationRule rule in (binding != null ? binding.ValidationRules : multiBinding.ValidationRules)) { ValidationResult result = rule.Validate(dependencyObject.GetValue(dependencyProperty), null); if (!result.IsValid) { BindingExpression bindingExpression = BindingOperations.GetBindingExpression(dependencyObject, dependencyProperty); MultiBindingExpression multiBindingExpression = null; if (bindingExpression == null) { multiBindingExpression = BindingOperations.GetMultiBindingExpression(dependencyObject, dependencyProperty); if (multiBindingExpression == null) { continue; } } BindingExpressionBase expression = bindingExpression ?? (BindingExpressionBase)multiBindingExpression; System.Windows.Controls.Validation.MarkInvalid(expression, new ValidationError(rule, expression, result.ErrorContent, null)); isValid = false; } } } return(isValid); }
private BindingBase GetExistingBinding(DeferredElement element) => BindingOperations.GetBinding(element.Element, element.DeferredProperty) ?? (BindingBase)BindingOperations.GetMultiBinding(element.Element, element.DeferredProperty);
private void ChangeToDeferredBinding(TextBox element) { var originalBinding = BindingOperations.GetBinding(element, TextBox.TextProperty) ?? (BindingBase)BindingOperations.GetMultiBinding(element, TextBox.TextProperty); SetOriginalBinding(element, originalBinding); SetInputDeferrer(element, this); var newBinding = CreateNewBinding(element); var text = (string)GetDeferredValue(element) ?? element.Text; if (text != element.Text && !ChangesAvailable) { text = element.Text; } //BindingOperations.ClearBinding(element, DeferredValueProperty); BindingOperations.ClearBinding(element, TextBox.TextProperty); element.SetValue(TextBox.TextProperty, text); //TODO: check if can remove the clear. BindingOperations.SetBinding(element, DeferredValueProperty, newBinding); }