0

i created 2 simple class like so:

public class Car { public int ID { get; set; } public string Name { get; set; } public string Model { get; set; } public string CheckInDateTime { get; set; } } public class CarDataSource { private static ObservableCollection<Car> _myCars=new ObservableCollection<Car>(); public static ObservableCollection<Car> GetCars() { if(_myCars.Count==0) { _myCars.Add(new Car() { ID = 1, Name = "A", Model = "Yamaha", }); _myCars.Add(new Car() { ID = 2, Name = "B", Model = "Toyota" }); _myCars.Add(new Car() { ID = 3, Name = "C", Model = "Suzuki" }); } return _myCars; } } 

In the MainPage.xaml.cs, I called the static GetCars() method to wire up the CarViewModel for the MainPage.xaml:

public ObservableCollection<Car> CarViewModel = CarDataSource.GetCars(); 

and finally is binding to the view model in xaml file:

<Page x:Class="BindingCommand.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:BindingCommand" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" DataContext="{Binding CarViewModel,RelativeSource={RelativeSource Self}}" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <Grid> <StackPanel> <ListView x:Name="myListView" ItemsSource="{Binding}"> <ListView.ItemTemplate> <DataTemplate x:Name="dataTemplate"> <StackPanel Orientation="Horizontal"> <StackPanel Orientation="Vertical" Margin="0,0,20,0"> <TextBlock Text="{Binding Make}" FontSize="24"/> <TextBlock Text="{Binding Model}" FontSize="24"/> </StackPanel> <Button Content="Check In" Width="100" Height="50" Margin="0,0,20,0"/> <TextBlock Text="{Binding CheckInDateTime}" FontSize="24"/> </StackPanel> </DataTemplate> </ListView.ItemTemplate> </ListView> </StackPanel> </Grid> 

but when i compliled and ran it, it showed me nothing. but then i fixed CarViewModel:

public ObservableCollection<Car> _CarViewModel = CarDataSource.GetCars(); public ObservableCollection<Car> CarViewModel { get { return this._CarViewModel;} } 

and it resulted as i want. I still don't know how it worked :|

1 Answer 1

4

Bindings in WPF/Xaml are always resolved against properties. In the first case, you had a public field, so the binding system didn't find a match for the path "CarViewModel". If you watched your output window when running in the debugger, there was probably a binding error there.

When you changed it to a property, the binding process was able to find it and it worked.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot for your point of view. Now i think i should learn about the differences between field and property :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.