Hie. I've currently got an attached property I use to get information from TextBoxes and alter it if need be. However it only works wit textBoxes meaning that user control elements such as ComboBoxes and DatePickers cannot be used with it. I'm not entirely sure where to alter it to get it to work with them too. Here's the class below.
public class TextBoxProperties
{
public static readonly DependencyProperty IsTextFormattedProperty = DependencyProperty.RegisterAttached("IsTextFormatted", typeof(bool), typeof(TextBoxProperties ), new UIPropertyMetadata(default(bool), OnIsTextFormattedChanged));
public static bool GetIsTextFormatted(DependencyObject dependencyObject)
{
return (bool)dependencyObject.GetValue(IsTextFormattedProperty);
}
public static void SetIsTextFormatted(DependencyObject dependencyObject, bool value)
{
dependencyObject.SetValue(IsTextFormattedProperty, value);
}
public static void OnIsTextFormattedChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
TextBox textBox = dependencyObject as TextBox;
ComboBox comboBox = dependencyObject as ComboBox;
// This will work fine...
if (textBox.Name == "firstNameTextBox")
{
bool newIsTextFormattedValue = (bool)dependencyPropertyChangedEventArgs.NewValue;
if (newIsTextFormattedValue) textBox.TextChanged += MyTextBoxChangedHandler;
else textBox.TextChanged -= MyTextBoxChangedHandler;
}
// This on the other hand will not
if (comboBox.Name == "genderTextBox")
{
bool newIsTextFormattedValue = (bool)dependencyPropertyChangedEventArgs.NewValue;
if (newIsTextFormattedValue) textBox.TextChanged += MyComboBoxChangedHandler;
else textBox.TextChanged -= MyComboBoxChangedHandler;
}
}
public static void MyTextBoxChangedHandler(object sender, TextChangedEventArgs e)
{
// Do what ever needs to be done with text...
}
public static void MyComboBoxChangedHandler(object sender, TextChangedEventArgs e)
{
// Do what ever needs to be done with text...
}
When using it I simply place this in the view's xaml:
<TextBox TextBoxProperties:IsFormatted="True" ... />
<ComboBox TextBoxProperties:IsFormatted="True" ... />
How ever When ever I add the Attached Property to a comboBox, I get the "Object reference not set to an instance of a object" error in the error window. If I run my app, it simply crashes with a first chance exception showing the same message.
Any clue on how to make it work?