0

I have some wpf windows, some classes and one viewmodel. Somehow, the value of the input field doesn't bind when I tell it to and the value in the viewmodel stays NULL.

I actually went on to use the value, but realized it has a NULL value during debugging.

In the input window:

<dx:ThemedWindow
    x:Class="DXEbayManager.NewProductsMenu"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:dx="http://schemas.devexpress.com/winfx/2008/xaml/core"
    Title="NewProductsMenu" Height="200" Width="450">

    <StackPanel>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="1*" />
                <ColumnDefinition Width="3*" />
            </Grid.ColumnDefinitions> 
            <Label Content="Product Name: " Grid.Column="0"/>
            <TextBox x:Name="ProductNameBox" Text="{Binding ProductName}" Grid.Column="1"/>
        </Grid>
    </StackPanel>
</dx:ThemedWindow>

In my ViewModel I have:

public class NewProductsMenuVM : ViewModelBase
    {
        public string ProductName { get; set; }
        public static NewProductsMenuVM Instance { get; } = new NewProductsMenuVM();
    }

And I would like to use the value here (where it is NULL):

    public partial class NewProductsMenu : ThemedWindow
    {        
        public void saveToDB()
        {
            string ProductName = NewProductsMenuVM.Instance.ProductName;
        }
    }

I don't have the best debugging skills, but the value after the {get; set; } was also already NULL. Why did this happen and what way is there around it?

Matthias G.
  • 61
  • 1
  • 11
  • 1
    Are you setting the data source of your window to the instance? – Haytam Aug 26 '19 at 14:35
  • 2
    How do you set the `DataContext` of your `ThemedWindow`? – mm8 Aug 26 '19 at 14:35
  • @mm8 From where I open it its: `var NewProducts = new NewProductsMenu { DataContext = DataContext }` and then `NewProducts.Show();` – Matthias G. Aug 26 '19 at 14:37
  • @mm8 You are absolutely right. I copied this piece code (the DataContext part) from an old answer I got and the person edited their response afterwards to the correct usage. Thanks for the answer! I will accept it as soon as possible. – Matthias G. Aug 26 '19 at 14:45

1 Answers1

1

You need to set the DataContext of your window to the NewProductsMenuVM instance somewhere, like for example in the constructor:

public partial class NewProductsMenu : ThemedWindow
{
    public NewProductsMenu()
    {
        InitializeComponent();
        DataContext = NewProductsMenuVM.Instance;
    }

    ...
    public void saveToDB()
    {
        string ProductName = NewProductsMenuVM.Instance.ProductName;
    }
}
mm8
  • 163,881
  • 10
  • 57
  • 88