如何将数据模板中的项目绑定到项目本身,而不是该项目的属性?
我有一个将项目作为模型的用户控件。鉴于这些模型:
public class Car
{
public string Name { get; set; }
public Color color { get; set; }
public string Model { get; set; }
}
public MyUserControl : UserControl
{
public Car Model { get; set; }
}
public MyPage : Page
{
public ObservableCollection<Car> CareList { get; set; }
}
我想在XAML中做这样的事情:
<ListView ItemsSource="{x:Bind CarList}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="models:Car">
<StackPanel>
<!-- Binding to properties of Car is simple... -->
<TextBlock Text="{x:Bind Name}">
<!-- But what if I want to bind to the car itself ??? -->
<userControls:MyUserControl Model="{x:Bind Car}">
</userControls:MyUserControl>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
答案 0 :(得分:0)
@ user2819245中的注释正确,如果您未指定绑定的Path
,则将直接绑定DataContext
对象。
在UWP中,如果列表源可以在运行时更改或延迟加载,则您可能还需要指定
Mode=OneWay
,这是由于{x:Bind}
默认为 OneTime < / em>绑定模式。此示例包括如何在两种用例中设置
Mode
属性
<ListView ItemsSource="{x:Bind CarList, Mode=OneWay}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="models:Car">
<StackPanel>
<!-- Binding to properties of Car is simple... -->
<TextBlock Text="{x:Bind Name, Mode=OneWay}">
<!-- Binding to the car itself (as the DataContext of this template) -->
<userControls:MyUserControl Model="{x:Bind Mode=OneWay}">
</userControls:MyUserControl>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>