1
votes

my model inside the shared project

class model
{
   public string title;
   public string link;
   public string pubDate;
   public string description;
   public string imageLink;
}

and my viewmodel inside the shared project

`class viewModel : INotifyPropertyChanged { public ObservableCollection _posts { get; set; }

    public ObservableCollection<model> posts {
        get {
           return _posts ;
        }
        set
        {
            _posts = value;
            RaisePropertyChanged("posts");
        }
    }


    public viewModel()
    {
        posts = new ObservableCollection<model>
        {
            new model { title="tiltle", description="description", link="link1" },
            new model { title="tiltle2", description="description2", link="link1" },
            new model { title="tiltle3", description="description3", link="link1" },
            new model { title="tiltle4", description="description4", link="link1" },
            new model { title="tiltle5", description="description5", link="link1" },
        };

    }

    public void RaisePropertyChanged(string prop)
    {
        if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(prop)); }
    }
    public event PropertyChangedEventHandler PropertyChanged;
}`

my xaml

<ListBox x:Name="listBoxControl" ItemsSource="{Binding}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <StackPanel>
                            <TextBlock Text="{Binding Path=title}" />
                            <TextBlock Text="{Binding Path=description}" />
                        </StackPanel>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

my xaml.cs

public MainPage()
    {
        this.InitializeComponent();
        this.DataContext = new viewModel();
       listBoxControl.DataContext = new viewModel().posts;

    }

this is my first question i i have problem with implement mvvm . however i have good understand about it when i run i did not see any thing

1

1 Answers

0
votes

Everything is fine except you should use properties with getters in your model then you will see something.

so:

class model
{
   public string title {get;set;}
   public string link  {get;set;}
   //etc..
}

because data binding works with Properties not fields.

on a side note: you do not need to name your ListBox or set its DataContext from code behind, you already did set the DataContext of your View to your ViewModel, so you can just bind to your ItemsSouce directly such as:

<ListBox ItemsSource="{Binding posts}">

even though the way you did it would work just fine.

also don't forget to implement INotifyPropertyChanged in your model if the property values change after initalization.