private static void OnPasteForDouble(object sender, DataObjectPastingEventArgs e) { var textBox = (TextBox)sender; var isText = e.SourceDataObject.GetDataPresent(DataFormats.Text, true); if (!isText) { return; } // Getting data from clipboard var clipboardText = (string)e.SourceDataObject.GetData(DataFormats.Text); // Lets create full text box text by current text box state and text from clipboard string text = CreateFullText(textBox, clipboardText); bool isValid = TextBoxDoubleValidator.IsValid(text); // If text is invalid we should cancel current command if (!isValid) { e.CancelCommand(); } }
private static void PreviewTextInputForDouble(object sender, TextCompositionEventArgs e) { var textBox = (TextBox)sender; // Unforortunately TextBox doesn't provide PreviewTextChanged event where we can get // full string that will be send to TextChanged event. // PreviewTextInput contains only new input in e.Text property. // But in some cases for validation we need full text but not only // new input, in this case we should create full text by hand. // Full text contains TextBox.Text WITHOUT selected text with e.Text string fullText = CreateFullText(textBox, e.Text); // Now fullText contains TextBox.Text that we'll have in TextChanged event bool isTextValid = TextBoxDoubleValidator.IsValid(fullText); // We'll stop text changed event if text is not a valid double e.Handled = !isTextValid; }