UWP ListView DataTemplate Bind to Item instead of Property

How do you bind an item in a data template to the item itself, instead of a property of that item?

I have a user control that takes an item as a model. Given these models:

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; }
}

I want to do something like this in 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>

Upvotes: 2

Views: 1265

Answers (1)

Chris Schaller
Chris Schaller

Reputation: 16554

The comment from @user2819245 is correct, if you do not specify the Path of the binding then the DataContext object will be bound directly instead.

In UWP, if your list source can change at runtime or is delay loaded, then you may also need to specify the Mode=OneWay, this is due to {x:Bind} defaulting to a OneTime binding mode.

This example includes how to set the Mode property in both use cases

<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>

Upvotes: 3

Related Questions