Note that there are some explanatory texts on larger screens.

plurals
  1. POCan't get DependencyProperty to work
    text
    copied!<p>I wrote a small attached property called "IsValid" for the WPF TextBox, like so:</p> <pre><code>public enum InputTypes { Any, Integer, Double, Float } /// &lt;summary&gt; /// This attached property can be used to validate input for &lt;see cref="TextBox"/&gt;. /// &lt;/summary&gt; public class IsValid : DependencyObject { public static readonly DependencyProperty InputProperty = DependencyProperty.Register( "Input", typeof(InputTypes), typeof(IsValid), new UIPropertyMetadata(InputTypes.Any, onInput)); public static InputTypes GetInput(DependencyObject d) { return (InputTypes)d.GetValue(InputProperty); } public static void SetInput(DependencyObject d, InputTypes value) { d.SetValue(InputProperty, value); } private static void onInput(DependencyObject d, DependencyPropertyChangedEventArgs e) { var textBox = (TextBox)d; var value = (InputTypes)e.NewValue; switch (value) { case InputTypes.Any: textBox.PreviewTextInput -= validateInput; textBox.PreviewKeyDown -= validateKeyDown; break; default: textBox.PreviewTextInput += validateInput; textBox.PreviewKeyDown += validateKeyDown; break; } } private static void validateInput(object sender, TextCompositionEventArgs e) { // enforce numeric input when configured ... var textBox = (TextBox) sender; var inputTypes = (InputTypes) textBox.GetValue(InputProperty); foreach (var c in e.Text) { switch (inputTypes) { case InputTypes.Integer: if (!char.IsDigit(c)) { e.Handled = true; return; } break; case InputTypes.Double: case InputTypes.Float: if (!char.IsNumber(c)) { e.Handled = true; return; } break; default: throw new ArgumentOutOfRangeException(); } } } private static void validateKeyDown(object sender, KeyEventArgs e) { // block [SPACE] when numeric input is expected ... var textBox = (TextBox)sender; var inputTypes = (InputTypes)textBox.GetValue(InputProperty); if (inputTypes != InputTypes.Any &amp;&amp; e.Key == Key.Space) e.Handled = true; } } </code></pre> <p>End here's how I've used it:</p> <pre><code>&lt;Window x:Class="Spike.Wpf.Controls.TestApp.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:values="clr-namespace:Spike.Wpf.Controls.Input;assembly=Spike.Wpf.Controls" Title="MainWindow" Height="350" Width="525"&gt; &lt;Grid&gt; &lt;TextBox values:IsValid.Input="Double" /&gt; &lt;/Grid&gt; </code></pre> <p></p> <p>After the initialization (of the <code>DependencyProperty</code>) none of the methods in <code>IsValid</code> gets called however. What am I missing?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload