我创建了2个简单的类:
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;
}
}
在MainPage.xaml.cs中,我调用静态GetCars()方法为MainPage.xaml连接CarViewModel:
public ObservableCollection<Car> CarViewModel = CarDataSource.GetCars();
最后绑定到xaml文件中的视图模型:
<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>
但是当我吵架并运行它时,它什么都没有给我看。 但后来我修复了CarViewModel:
public ObservableCollection<Car> _CarViewModel = CarDataSource.GetCars();
public ObservableCollection<Car> CarViewModel
{
get { return this._CarViewModel;}
}
它按照我想要的结果。 我仍然不知道它是如何工作的:|
答案 0 :(得分:4)
WPF / Xaml中的绑定始终针对属性进行解析。在第一种情况下,您有一个公共字段,因此绑定系统找不到路径“CarViewModel”的匹配项。如果您在调试器中运行时观察了输出窗口,那么可能存在绑定错误。
当您将其更改为属性时,绑定过程能够找到它并且它有效。