Skip to content

x:Bind outside data templates is extremely inconsistent #2508

@Sergio0694

Description

@Sergio0694

Describe the bug

Apparently it is possible to use x:Bind to bind to a field in code behind outside a data template. Basically, escaping from the data template in use. Not entirely sure whether this is by design or just a lucky quirk of the XAML compiler and codegen (especially since this is not mentioned anywhere in the docs), but it works.

As a code example:

<UserControl
    x:Class="MyNamespace.Views.MyUserControl"
    xmlns:viewModels="using:MyNamespace.ViewModels"
    models="using:MyNamespace.Models">
    <UserControl.DataContext>
        <viewModels:MyViewModel x:Name="ViewModel"/>
    </UserControl.DataContext>
    <UserControl.Resources>

        <DataTemplate
            x:Name="SomeDataTemplate"
            x:DataTye="models:SomeModelTyppe">

            <!--This works-->
            <TextBlock Text="{x:Bind ViewModel.SomeText}"/>
        </DataTemplate>
    </UserControl.Resources>

    <ListView
        ItemsSource="{x:Bind ViewModel.MyItems}"
        ItemTemplate="{StaticResource SomeDataTemplate}"/>
</UserControl>

You can see how the binding is escaping the data template and just targeting a field in code behind.
The problem with this is that it's extremely fragile and inconsistent:

  • x:Bind to a property outside the data template works fine ✅
  • x:Bind to that same property but with function binding fails to build ❌
  • x:Bind to that same property from a visual state setter crashes at runtime ❌
  • x:Bind to that same property with a converter crashes at runtime ❌

Steps to reproduce the bug

Steps to reproduce the behavior:

  1. Download this repro
  2. Open the solution, run the app

Expected behavior

🤷‍♂️ 🤷‍♂️ 🤷‍♂️

Actual behavior

The binding to the outside field (the view model) works just fine

Screenshots

image

Windows 10 version Saw the problem?
Insider Build (xxxxx)
November 2019 Update (18363) Yes
May 2019 Update (18362) Yes
October 2018 Update (17763)
April 2018 Update (17134)
Fall Creators Update (16299)
Creators Update (15063)
Device form factor Saw the problem?
Desktop Yes
Mobile
Xbox
Surface Hub
IoT

cc. @MikeHillberg

Sub-issues

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    Ready

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions