Hackawar
Hackawar

Reputation: 25

Property returning null unless It's bound?

         Window2 X = new Window2();
        var taskViewModel = (XViewModel)X.DataContext;
        taskViewModel.Name = Username;
        X.Show();

I struggled for hours thinking that the above code is not working properly while It was. Because If I bind Name to a Textblock for example in the second form, the value is going to show. If I write it using Console.Write or try to show it in a MessageBox It returns null, nothing is shown. What is causing that?

 public string Name
      {
          get { return _Name; }
          set
          {
              _Name = value;
              NotifyOfPropertyChange("Name");
          }
      }

     Public XViewModel()
    {
        MessageBox.Show(Name);
    }

As simpel as that, the above messageBox will be empty. If I do this however:

<TextBlock FontWeight="Bold" Text="{Binding Name}" ></TextBlock>

It's going to show properly as soon as I open the window using the first code.

EDIT: I tried to make a button and binded a command that calls the MessageBox. In this case, Name is showing propertly.

EDIT2: this is not working either:

        Window2 w = new Window2();
        XViewModel vm = new XViewModel ();
        vm.Name = Username;
        w.DataContext = vm;
        w.Show();

Upvotes: 0

Views: 83

Answers (1)

Babbillumpa
Babbillumpa

Reputation: 1864

The problem is that you are tring to show Name inside the constructor that is before you set the property:

    // Here i think you are creating XViewModel
    Window2 X = new Window2();

    //Here where the Messagebox shows

    var taskViewModel = (XViewModel)X.DataContext;

    //Here you set the property
    taskViewModel.Name = Username;

    // Now the value is correctly shown in the textblock
    X.Show();

Try setting the value of the property after you create the object XViewModel:

public class Window2
{
   public Window2(XViewModel vm)
   {
       InitializeComponent();

       DataContext = vm;
   }
}

EDIT:

Let's do something else:

Define XViewModel class this way:

public class XViewModel
{
   public XViewModel(String nameProp)
   {
      Name = nameProp;
      MessageBox.Show(Name);
    }
   // Your Properties
   // Your Methods
}


// Create XViewModel and pass it to Window 2
var taskViewModel = new XViewModel(Username);   //HERE where messagebox shows

Window2 X = new Window2(taskViewModel);

// Now the value is correct shown in the textblock
X.Show();

Upvotes: 2

Related Questions