1
votes

Im building a WPF application using MVVM Pattern but i 've been testing even for simple binding and i dont get it work the code is basically like this:

I think that the problem is in the xaml Bindings Model:

public class Product
{
    private string modelNumber;
    public string ModelNumber
    {
        get { return modelNumber; }
        set { modelNumber = value; }
    }
    private string modelName;
    public string ModelName
    {
        get { return modelName; }
        set { modelName = value; }
    }
    private decimal unitCost;
    public decimal UnitCost
    {
        get { return unitCost; }
        set { unitCost = value; }
    }
    private string description;
    public string Description
    {
        get { return description; }
        set { description = value; }
    }
    public Product(string modelNumber, string modelName,      decimal unitCost, string description)
    {
        ModelNumber = modelNumber;
        ModelName = modelName;
        UnitCost = unitCost;
        Description = description;
    }

    public static Product GetProduct()
    {
        return new Product("1","A6",20000,"Description");
    }
}

ViewModel:

  class ProductViewModel
    {
        public Product p;
        public ProductViewModel()
        {
           p= Product.GetProduct();

        }

    }

Xaml:

<Grid Name="gridProductDetails" >

    <TextBlock Margin="7">Model Number:</TextBlock>
    <TextBox Margin="5" Grid.Column="1" Grid.ColumnSpan="2" Text="{Binding p.ModelNumber}" ></TextBox>

</Grid>

Code Behind:

        private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        gridProductDetails.DataContext = new ProductViewModel();
    }
1
"but i 've been testing even for simple binding and i dont get it work" I don't believe you. I read your question and it has absolutely no information about what you did, what you expected to happen, and what actually did happen. Therefore, as far as I can tell, everything worked as expected. Of course, you could edit to include these details and prove me a liar. Also, your properties don't implement INotifyPropertyChanged so the UI won't update automatically when values change in the view model.user1228

1 Answers

2
votes

Please update the following that should solve your problem:

  1. Mark ProductViewModel as public
  2. Convert variable p to auto property. public Product p { get; set; }

Regards