public static bool IsValidRules(DependencyObject parent) { // Validate all the bindings on the parent bool valid = true; LocalValueEnumerator localValues = parent.GetLocalValueEnumerator(); while (localValues.MoveNext()) { LocalValueEntry entry = localValues.Current; if (BindingOperations.IsDataBound(parent, entry.Property)) { Binding binding = BindingOperations.GetBinding(parent, entry.Property); foreach (ValidationRule rule in binding.ValidationRules) { ValidationResult result = rule.Validate(parent.GetValue(entry.Property), null); if (!result.IsValid) { BindingExpression expression = BindingOperations.GetBindingExpression(parent, entry.Property); System.Windows.Controls.Validation.MarkInvalid(expression, new ValidationError(rule, expression, result.ErrorContent, null)); valid = false; } } } } // Validate all the bindings on the children for (int i = 0; i != VisualTreeHelper.GetChildrenCount(parent); ++i) { DependencyObject child = VisualTreeHelper.GetChild(parent, i); if (!IsValid(child)) { valid = false; } } return(valid); }
private static void OnInheritInputBindingFromMainWindowChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (!(d is UIFrameworkElement frameworkElement)) { throw new Exception("In order to inherit the shortcuts from the MainWindow, a binding must be created between " + "the InputBindingProperty of the UIElement and the InputBindingContext of the MainWindow." + "Only FrameWorkElements support binding."); } var mainWindow = Application.Current.MainWindow; var shortcutsBinding = BindingOperations.GetBinding(mainWindow, ShortcutsProperty); var currentBinding = BindingOperations.GetBinding(frameworkElement, ShortcutsProperty); if (shortcutsBinding != null) { if (e.NewValue.Equals(true)) { if (currentBinding != null) { BindingOperations.ClearBinding(frameworkElement, ShortcutsProperty); } frameworkElement.SetBinding(ShortcutsProperty, new Binding() { Path = shortcutsBinding.Path, Source = mainWindow.DataContext, }); } else { if (currentBinding != null && currentBinding.Source == shortcutsBinding.Source && currentBinding.Path == shortcutsBinding.Path) { BindingOperations.ClearBinding(frameworkElement, ShortcutsProperty); } } } }
private static void OnIsActivePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (_defaultProperties.ContainsKey(d.GetType())) { var defaultProperty = _defaultProperties[d.GetType()]; if ((bool)e.NewValue) { var binding = BindingOperations.GetBinding(d, defaultProperty); if (binding != null) { var bindingPath = binding.Path.Path; BindingOperations.SetBinding(d, IsChangedProperty, new Binding(bindingPath + "IsChanged")); CreateOriginalValueBinding(d, bindingPath + "OriginalValue"); } } else { BindingOperations.ClearBinding(d, IsChangedProperty); BindingOperations.ClearBinding(d, OriginalValueProperty); } } }
void RebuildThemePropertyList() { if (this.ThemeObject != null) { var props = this.ThemeObject.GetType().GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance) .Where(pi => pi.GetCustomAttributes(typeof(ThemePropertyAttribute), false).Length > 0) .Select(pi => new ThemeProperty(pi, ((ThemePropertyAttribute)pi.GetCustomAttributes(typeof(ThemePropertyAttribute), false)[0]).Category)) .ToList(); this.ThemeProperties = props; foreach (var tp in props) { var binding = BindingOperations.GetBinding(this.ThemeObject, Theme.Instance.Theme.LookupThemeProperty(tp.PropertyInfo.Name)); if (binding != null && binding.Source is PaletteColor) { tp.PaletteItemName = ((PaletteColor)binding.Source).Name; } } } else { this.ThemeProperties = Enumerable.Empty <ThemeProperty>(); } this.ThemePropertySource = new CollectionViewSource() { Source = this.ThemeProperties }; this.ThemePropertySource.SortDescriptions.Add(new SortDescription { PropertyName = "Category" }); this.ThemePropertySource.SortDescriptions.Add(new SortDescription { PropertyName = "Name" }); this.ThemePropertySource.GroupDescriptions.Add(new PropertyGroupDescription { PropertyName = "Category" }); this.ThemePropertySource.Filter += OnThemePropertySourceFilter; }
protected void BuildCommonBinding(DependencyProperty sourceProperty, DependencyProperty targetProperty) { string mappingString = (string)GetValue(sourceProperty); if (String.IsNullOrEmpty(mappingString)) { return; } PropertyDescriptor propDescriptor = CreatePropertyDescriptor(mappingString); IValueConverter converter = null; // trying to find appropriate value converter if (propDescriptor != null && propDescriptor.PropertyType != typeof(double)) { ValueConverterFactoriesStore store = ValueConverterFactoriesStore.Current; converter = store.TryBuildConverter(propDescriptor.PropertyType, Plotter); } // if ValueMapping has a value if ((string)GetValue(sourceProperty) != (string)sourceProperty.DefaultMetadata.DefaultValue) { // try build a binding for value using ValueMapping var existingBinding = BindingOperations.GetBinding(this, targetProperty); if (true || existingBinding != null) { Binding binding = new Binding { Path = new PropertyPath((string)GetValue(sourceProperty)) }; if (converter != null) { binding.Converter = converter; } bindingInfos[targetProperty] = binding; } } }
private void OnIconForegroundChanged() { if (_iconPresenter != null) { if (IconForeground != null) { var bindingProperty = BindingOperations.GetBinding(Source, IconHelper.ForegroundProperty)?.Path?.PathParameters?.FirstOrDefault() as DependencyProperty; if (bindingProperty != null && bindingProperty.OwnerType == typeof(Internal.VisualStateHelper)) { _iconPresenter.Foreground = IconForeground; } } else { var bindingProperty = BindingOperations.GetBinding(Source, IconHelper.ForegroundProperty)?.Path?.PathParameters?.FirstOrDefault() as DependencyProperty; if (bindingProperty != null && bindingProperty.OwnerType == typeof(Internal.VisualStateHelper)) { FrameworkElementUtil.BindingProperty(_iconPresenter, IconPresenter.ForegroundProperty, Source, IconHelper.ForegroundProperty); } } } }
/// <summary> /// Checks if Source and OpacityMask properties of an image are databoud /// and if so caches and clears these bindings. Then it clones these /// bindings and sets them on an image to attached Source and OpacityMask /// properties registered for this class. /// This allows to keep the binding working while the Source and OpacityMask /// properties of an image are been set directly from code when image is /// enabled or disabled. /// </summary> private void StealBinding() { if (BindingOperations.IsDataBound(this, Image.SourceProperty)) { _sourceBinding = BindingOperations.GetBinding(this, Image.SourceProperty); BindingOperations.ClearBinding(this, Image.SourceProperty); Binding b = CloneBinding(_sourceBinding); b.Mode = BindingMode.OneWay; this.SetBinding(SourceProxyProperty, b); } if (BindingOperations.IsDataBound(this, Image.OpacityMaskProperty)) { _opacityMaskBinding = BindingOperations.GetBinding(this, Image.OpacityMaskProperty); BindingOperations.ClearBinding(this, Image.OpacityMaskProperty); Binding b = CloneBinding(_opacityMaskBinding); b.Mode = BindingMode.OneWay; this.SetBinding(OpacityMaskProxyProperty, b); } }
IEnumerable <IElement> CheckHeaderedItemsControl(ICollection <string> checkedProperties, ElementEnumeratorSettings settings) { if (!settings.IncludeTemplates) { yield break; } var headeredItemsControl = Element as HeaderedItemsControl; if (headeredItemsControl != null) { checkedProperties.Add(HeaderedContentControl.HeaderTemplateProperty.Name); var template = headeredItemsControl.HeaderTemplate; if (template != null) { var dataType = template.DataType as Type; if (dataType == null) { var binding = BindingOperations.GetBinding( headeredItemsControl, HeaderedItemsControl.HeaderProperty ); if (binding != null) { yield return(Bound.DataTemplate(template, Type.GetAssociatedType(binding.Path.Path), Name)); } } else { yield return(Bound.DataTemplate(template, new BoundType(dataType), Name)); } } } }
protected override bool ApplyInline(DataColumnBase column, object data, bool ApplySearchHighlightBrush) { IEnumerable <string> searchTexts = GetSearchStrings().Select(Regex.Escape); var success = false; var regex = new Regex($"({string.Join("|", searchTexts)})", RegexOptions.IgnoreCase); TextBlock[] textControls = FindObjectInVisualTreeDown <TextBlock>(column.ColumnElement).ToArray(); if (!textControls.Any()) { return(base.ApplyInline(column, data, ApplySearchHighlightBrush)); } TextBlock textBlock = textControls.First(); Binding binding = BindingOperations.GetBinding(textBlock, TextBlock.TextProperty); string[] substrings = regex.Split(data.ToString()); textBlock.Inlines.Clear(); Binding binding1 = BindingOperations.GetBinding(textBlock, TextBlock.TextProperty); foreach (string item in substrings) { if (regex.Match(item).Success) { var run = new Run(item); run.Background = SearchBrush; textBlock.Inlines.Add(run); success = true; } else { textBlock.Inlines.Add(item); } } return(success); }
public void SetTextValueBySelection(object obj, bool moveFocus) { if (popup != null) { InternalClosePopup(); Dispatcher.Invoke(new Action(() => { Focus(); if (moveFocus) { MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); } }), System.Windows.Threading.DispatcherPriority.Background); } Text = (obj is ENFERMEDAD) ? ((ENFERMEDAD)obj).NOMBRE : (obj is DIETA) ? ((DIETA)obj).DESCR : dummy.GetValue(TextProperty).ToString(); // Retrieve the Binding object from the control. var originalBinding = BindingOperations.GetBinding(this, BindingProperty); if (originalBinding == null) { return; } // Set the dummy's DataContext to our selected object. dummy.DataContext = obj; // Apply the binding to the dummy FrameworkElement. BindingOperations.SetBinding(dummy, TextProperty, originalBinding); suppressEvent = true; // Get the binding's resulting value. suppressEvent = false; listBox.SelectedIndex = -1; SelectAll(); }
private static void OnValidationTypeChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { var element = obj as FrameworkElement; if (element == null) { return; } // When the element has loaded. element.Loaded += (s, e) => { var valid = new ValidationHelper(GetValidationType(obj), GetMinValue(obj), GetMaxValue(obj), GetMinLength(obj), GetMaxLength(obj), GetOnlyCharacters(obj), GetOnlyHex(obj), GetNoEmptyValue(obj)); Binding bind = BindingOperations.GetBinding(obj, TextBox.TextProperty); if (bind != null) { if (!bind.ValidationRules.Contains(valid)) { bind.ValidationRules.Add(valid); } } }; }
/// <summary> /// TextBlockのLoadedイベント /// </summary> private static void TextBlock_Loaded(object sender, EventArgs e) { var textblock = sender as TextBlock; if (textblock == null) { return; } var binding = BindingOperations.GetBinding(textblock, TextBlock.TextProperty); if (binding == null) { return; } // Textプロパティ変更時に通知されるようにする BindingOperations.SetBinding(textblock, TextBlock.TextProperty, new Binding() { Path = binding.Path, NotifyOnTargetUpdated = true }); }
/// <summary> /// Handles changes to the BindParameter property. /// </summary> private static void OnBindParameterChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { FrameworkElement element = d as FrameworkElement; if (element == null) { throw new InvalidOperationException("BindableParameter can be applied to a FrameworkElement only"); } BindableParameter parameter = (BindableParameter)e.NewValue; if (parameter != null) { element.Initialized += delegate { parameter.TargetExpression = BindingOperations.GetBindingExpression(element, parameter.TargetProperty); parameter.TargetBinding = BindingOperations.GetBinding(element, parameter.TargetProperty); //update the converter parameter InvalidateBinding(parameter); }; } }
private void purchaseTickets_Click(object sender, RoutedEventArgs e) { BindingExpression eventBe = eventList.GetBindingExpression(ComboBox.TextProperty); BindingExpression customerReferenceBe = customerReference.GetBindingExpression(TextBox.TextProperty); BindingExpression privilegeLevelBe = privilegeLevel.GetBindingExpression(ComboBox.TextProperty); BindingExpression numberOfTicketsBe = numberOfTickets.GetBindingExpression(Slider.ValueProperty); eventBe.UpdateSource(); customerReferenceBe.UpdateSource(); privilegeLevelBe.UpdateSource(); numberOfTicketsBe.UpdateSource(); if (eventBe.HasError || customerReferenceBe.HasError || privilegeLevelBe.HasError || numberOfTicketsBe.HasError) { MessageBox.Show("Please correct errors", "Purchase Aborted"); } else { Binding ticketOrderBinding = BindingOperations.GetBinding(privilegeLevel, ComboBox.TextProperty); TicketOrder ticketOrder = ticketOrderBinding.Source as TicketOrder; MessageBox.Show(ticketOrder.ToString(), "Purchased"); } }
/// <summary> /// Initializes a new instance of the <see cref="ColumnPanelColumnDefinition"/> class. /// </summary> /// <param name="column">The column.</param> public ColumnPanelColumnDefinition(ColumnDefinition column) { var binding = BindingOperations.GetBinding(column, WidthProperty); if (binding == null) { Width = column.Width; } else { SetBinding(WidthProperty, binding); } var descriptor = DependencyPropertyDescriptor.FromProperty(WidthProperty, typeof(ColumnDefinition)); descriptor.AddValueChanged(this, (o, e) => { if (WidthChanged != null) { WidthChanged(this, new EventArgs()); } }); }
// registers the parameter value change while keeping text box focused on private void TextBox_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { var textBox = sender as TextBox; var expression = BindingOperations.GetBindingExpression(textBox, TextBox.TextProperty); expression.UpdateSource(); // this is overly specific to numeric text boxes, like the ones in the loop stream provider // I should get rid of it as soon as I make proper watermarked textboxes // so that the text for defaults is *always* an empty string // and if the text is empty string, the watermark displays var binding = BindingOperations.GetBinding(textBox, TextBox.TextProperty); if (binding.Converter is Converters.NumericWithDefaultConverter) { if (binding.ConverterParameter.Equals(textBox.Text)) { textBox.Text = ""; } } } }
/// <summary> /// Adapts a <see cref="TransitionElement"/> to an <see cref="IRegion"/>. /// </summary> /// <param name="region">The new region being used.</param> /// <param name="regionTarget">The object to adapt.</param> protected override void Adapt(IRegion region, TransitionElement regionTarget) { if (regionTarget == null) { throw new ArgumentNullException(nameof(regionTarget)); } bool contentIsSet = regionTarget.Content != null; contentIsSet = contentIsSet || (BindingOperations.GetBinding(regionTarget, TransitionElement.ContentProperty) != null); if (contentIsSet) { throw new InvalidOperationException("The Transition Element already contains content"); } region.ActiveViews.CollectionChanged += delegate { var view = region.ActiveViews.FirstOrDefault(); // Don't use null views :) if (view != null) { regionTarget.Content = view; } }; region.Views.CollectionChanged += (sender, e) => { if (e.Action == NotifyCollectionChangedAction.Add && region.ActiveViews.Count() == 0) { region.Activate(e.NewItems[0]); } }; }
private void checkBoxPostcode0_Click(object sender, RoutedEventArgs e) { Binding binding1 = BindingOperations.GetBinding(postcodeTextBox, TextBox.TextProperty); binding1.ValidationRules.Clear(); var binding2 = (postcodeColumn as DataGridBoundColumn).Binding as Binding; binding2.ValidationRules.Clear(); brouwerDataGrid.RowValidationRules.Clear(); switch (checkBoxPostcode0.IsChecked) { case true: binding1.ValidationRules.Add(new PostcodeRangeRule0()); binding2.ValidationRules.Add(new PostcodeRangeRule0()); brouwerDataGrid.RowValidationRules.Add(new PostcodeRangeRule0()); break; case false: binding1.ValidationRules.Add(new PostcodeRangeRule()); binding2.ValidationRules.Add(new PostcodeRangeRule()); brouwerDataGrid.RowValidationRules.Add(new PostcodeRangeRule()); break; default: binding1.ValidationRules.Add(new PostcodeRangeRule()); binding2.ValidationRules.Add(new PostcodeRangeRule()); brouwerDataGrid.RowValidationRules.Add(new PostcodeRangeRule()); break; } //binding1.ValidationRules[0].ValidatesOnTargetUpdated = true; //binding1.ValidationRules[0].ValidationStep = ValidationStep.UpdatedValue; //binding2.ValidationRules[0].ValidatesOnTargetUpdated = true; //binding2.ValidationRules[0].ValidationStep = ValidationStep.UpdatedValue; //brouwerDataGrid.RowValidationRules[0].ValidatesOnTargetUpdated = true; //brouwerDataGrid.RowValidationRules[0].ValidationStep = ValidationStep.UpdatedValue; }
static void ItemsSourcePropertyChanged(DependencyObject element, DependencyPropertyChangedEventArgs e) { var target = element as Selector; if (element == null) { return; } var originalBinding = BindingOperations.GetBinding(target, Selector.SelectedValueProperty); BindingOperations.ClearBinding(target, Selector.SelectedValueProperty); try { target.ItemsSource = e.NewValue as IEnumerable; } finally { if (originalBinding != null) { BindingOperations.SetBinding(target, Selector.SelectedValueProperty, originalBinding); } } }
private static void ItemsSourcePropertyChanged(DependencyObject element, DependencyPropertyChangedEventArgs e) { var target = element as ComboBox; if (element == null) { return; } // Save original binding var originalBinding = BindingOperations.GetBinding(target, ComboBox.TextProperty); BindingOperations.ClearBinding(target, ComboBox.TextProperty); try { target.ItemsSource = e.NewValue as IEnumerable; } finally { if (originalBinding != null) { BindingOperations.SetBinding(target, ComboBox.TextProperty, originalBinding); } } }
/// <summary> /// Validations the rule text box2 changed. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="DependencyPropertyChangedEventArgs"/> instance containing the event data.</param> private static void ValidationRuleTextBox2Changed(DependencyObject sender, DependencyPropertyChangedEventArgs e) { var textBoxesSmallControl = sender as TextBoxesSmallControl; if (textBoxesSmallControl != null) { Binding binding = BindingOperations.GetBinding(textBoxesSmallControl.TextBox2, TextBox.TextProperty); if (binding == null) { return; } binding.ValidationRules.Clear(); // In case multiple rules are bound then it would come like "Required|Numeric var validationRules = textBoxesSmallControl.ValidationRuleTextBox2.Split(new[] { "|", }, StringSplitOptions.RemoveEmptyEntries); foreach (var rule in validationRules) { textBoxesSmallControl.RegisterRule(rule, textBoxesSmallControl.TextBox2, textBoxesSmallControl.IntRangeRuleMinValueTextBox2, textBoxesSmallControl.IntRangeRuleMaxValueTextBox2); } } }
private void Configure() { Dispatcher.Invoke(DispatcherPriority.Render, _emptyDelegate); var binding = BindingOperations.GetBinding(this, SourceProperty); if (binding == null) { return; } var previousBinding = GetPreviousFieldBinding(this); if (previousBinding == binding) { return; } SetPreviousFieldBinding(this, binding); var bindingEx = BindingOperations.GetBindingExpression(this, SourceProperty); if (bindingEx == null) { return; } var type = bindingEx.ResolvedSource.GetType(); var property = type.GetProperty(bindingEx.ResolvedSourcePropertyName); var input = GenerateInputField(property, binding, bindingEx); Content = new AdornerDecorator { Child = input }; }
private void ShowWatermark() { if (String.IsNullOrEmpty(Text) && !String.IsNullOrEmpty(Watermark) && IsEnabled) { _isWatermarked = true; //save the existing binding so it can be restored //second fix: save it in a dependency property so that we get a changed notification if this control's bound value changes (crucial!) var txt = BindingOperations.GetBinding(this, TextProperty); if (txt != null) { SetBinding(SaveTextProperty, txt); } //blank out the existing binding so we can throw in our Watermark BindingOperations.ClearBinding(this, TextProperty); //set the signature watermark gray Foreground = new SolidColorBrush(Colors.Gray); //display our watermark text Text = Watermark; } }
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); }
private static void OnIsActivatedPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (!(d is TextBox)) { return; } var binding = BindingOperations.GetBinding(d, TextBox.TextProperty); if (binding == null) { return; } if ((bool)e.NewValue) { var sourceObject = binding.Path.Path; //TODO: } else { //TODO: } }
private void takespec(object sender, RoutedEventArgs e) { MenuItem mnu = sender as MenuItem; TextBox sp = null; if (mnu != null) { sp = ((ContextMenu)mnu.Parent).PlacementTarget as TextBox; if (System.Windows.MessageBox.Show("Daten wirklich übernehmen?", "", MessageBoxButton.YesNo , MessageBoxImage.Question) == MessageBoxResult.Yes) { Binding myBinding = BindingOperations.GetBinding(sp, TextBox.TextProperty); string boundComponent = myBinding.Path.Path.Remove(0, 3); System.Reflection.PropertyInfo prop = typeof(ViewModels.PToshibaVM).GetProperty(boundComponent); for (int i = index + 1; i < index + test + 1; i++) { if (sp.Text != "") { prop.SetValue(m_vm.Processes[i], Convert.ToDouble(sp.Text.Replace('.', ',')), null); } else { prop.SetValue(m_vm.Processes[i], null, null); } } } //property.SetValue(Convert.ToDouble(sp.Text.Replace('.',',')), "...", null); } //MessageBox.Show(" Textbox:" + sp.Name); }
private void btVerhuur_Click(object sender, RoutedEventArgs e) { Binding b = BindingOperations.GetBinding(inVoorraadTextBox, TextBox.TextProperty); b.ValidationRules.Clear(); int inVoorraad = Convert.ToInt32(inVoorraadTextBox.Text); int uitVoorraad = Convert.ToInt32(uitVoorraadTextBox.Text); int totaalVerh = Convert.ToInt32(totaalVerhuurdTextBox.Text); if (inVoorraad > 0) { inVoorraadTextBox.Text = (inVoorraad - 1).ToString(); uitVoorraadTextBox.Text = (uitVoorraad + 1).ToString(); totaalVerhuurdTextBox.Text = (totaalVerh + 1).ToString(); } else { MessageBox.Show("Alle films zijn verhuurd!!!", "Verhuur", MessageBoxButton.OK, MessageBoxImage.Asterisk); } b.ValidationRules.Add(new GetalGroterDanNulRule()); b.ValidationRules.Add(new IntGetalIngaveRule()); }
public void VuldeGridLokaal() { var genres = (from filmpje in filmsOb orderby filmpje.Genre select filmpje.Genre).Distinct().ToList(); genres.Insert(0, ""); comboBoxGenres.ItemsSource = genres; buttonAllesOpslaan.IsEnabled = true; buttonVerhuur.IsEnabled = true; buttonToevoegen.Content = "Toevoegen"; buttonVerwijderen.Content = "Verwijderen"; listBoxTitels.SelectedIndex = 0; //binding vinden Binding binding2 = BindingOperations.GetBinding(inVoorraadTextBox, TextBox.TextProperty); //verwijder validationRules binding2.ValidationRules.Clear(); //toevoegen nieuwe validionRule: binding2.ValidationRules.Add(new InVoorraadValidation()); //scrollview listBoxTitels.ScrollIntoView(listBoxTitels.SelectedItem); }
/// <summary> /// Associates the current framework element with the label that is stored in the element's /// dependency property <see cref="Property.LabelProperty"/>, which can be statically set in XAML. /// Default implementation sets the current element as the target for the label and also sets /// the label text on the data property from the corresponding label control if not already set. /// </summary> protected override void SetLabel() { object lbl = element.GetValue(Property.LabelProperty); // if it is a label, set its target to this element unless it's already set Label elLbl = lbl as Label; if (elLbl != null && elLbl.Target == null && BindingOperations.GetBinding(elLbl, Label.TargetProperty) == null) { elLbl.Target = element as UIElement; } // set property label if it is not already set and if associated label is present string lblTxt = null; if (lbl is ContentControl) { lblTxt = "" + ((ContentControl)lbl).Content; } else if (lbl is TextBlock) { lblTxt = ((TextBlock)lbl).Text; } SetPropertyLabel(lblTxt); }
private static void Pred_Changed(DependencyObject obj, Func <string, ValidationResult> new_value, Func <string, ValidationResult> old_value) { // Reflect on 'obj' for the TextProperty dependency property var fi = obj.GetType().GetField(nameof(TextBox.TextProperty), BindingFlags.Static | BindingFlags.Public); if (fi == null) { throw new Exception($"Type {obj.GetType().Name} does not have a static dependency property '{nameof(TextBox.TextProperty)}'"); } // Get the binding to the TextProperty var dep = (DependencyProperty?)fi.GetValue(null); var binding = BindingOperations.GetBinding(obj, dep); // Add/Replace/Remove the predicate validator if (old_value != null) { binding.ValidationRules.RemoveIf(x => x is TextValidator tv && tv.Pred == old_value); } if (new_value != null) { binding.ValidationRules.Add(new TextValidator(new_value)); } }