[英]XAML: Confusing about binding
我創建了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;}
}
結果就是我想要的。 我仍然不知道它是如何工作的:|
WPF / Xaml中的綁定始終針對屬性進行解析。 在第一種情況下,您有一個公共字段,因此綁定系統找不到與路徑“ CarViewModel”匹配的項。 如果在調試器中運行時觀察了輸出窗口,則可能是綁定錯誤。
當您將其更改為屬性時,綁定過程便能夠找到它並且可以正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.