nullreferenceexceptionmaskmaskedtextbox

MaskedTextBox Extended Wpf Toolkit


I have a problem with MaskedTextBox that comes from Extended Wpf Toolkit. So, when i use it instead of TextBox there is an error - Null Reference Exception. Then i searched the reason and finally found it. When i use MaskedTextBox with Mask Property

<xctk:MaskedTextBox
      Name="txtMessage"
      Value="{Binding Message, UpdateSourceTrigger=PropertyChanged}"
      IncludeLiteralsInValue="False"
      Mask="(000)000-00-00"
      TextBoxBase.TextChanged="txtMessage_TextChanged" 
      ValueDataType="{x:Type s:String}">

it causes Null Reference Exception because DataContext of UserControl is null, but I don't know why, the Constructor of UserControl has something like this:

  editModel = new EditViewModel();
  DataContext = editModel;

And editModel is null. But When I delete Mask property everything works fine. Can you help me pls.


Solution

  • The Problem was that Mask Property of MaskedTextBox is bind to a Text Property of TextBox. So when Xaml page generates, app tries bind Mask property to the Message, but in this moment ViewModel is not created and so occurs a 'NullReferenceException'.
    The Solution is that you must set the Mask property of MaskedTextBox not in Xaml, and after declaring your ViewModel.
    editModel = new EditViewModel(); DataContext = editModel; txtMessage.Mask = "(000)00-000-00-00";