microsoft-ui-xaml: x:Bind outside data templates is extremely inconsistent

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

About this issue

  • Original URL
  • State: open
  • Created 7 years ago
  • Reactions: 23
  • Comments: 42 (20 by maintainers)

Most upvoted comments

Seems related to #2237 as well?

My latest trick is to do something like this:

<Page x:Name="ThisPage"...>
   <ItemsControl>
       <ItemsControl.ItemTemplate>
           <DataTemplate x:DataType="local:MyType">
               <Button Command="{Binding ViewModel.SaveCommand, ElementName=ThisPage}" CommandParameter="{x:Bind (local:MyType)}"/>

But x:Bind should just let us break into the different scopes we need:

  • Local (data item itself)
  • Container (ListViewItem for instance)
  • “Parent” (ListView for instance)
  • “Global” (i.e. Page)

I think that’d cover the majority of scenarios I ever need when dealing with templating. The compiler should just be able to walk the scope up if it’s not finding the reference path at each tier.

Will call out that this type of issue will prevent adoption of AoT as the fallback is to do things with regular Binding or alternatives compared to keeping things sleek and simple with x:Bind. Linked an issue we have with a sample from the WCT in a related but also tangential issue with ItemsPanelTemplate. See the related issue we filed here for that: https://github.com/microsoft/microsoft-ui-xaml/issues/10070

Not sure whether this is a regression and if so, when it was introduced, but now I can’t even get the only scenario that was working back when I first opened this issue to work at all anymore. Even just binding to the top viewmodel in a page fails to build. This is a pretty big issue because it blocks many scenarios where you need a backlink to a parent viewmodel for shared functionality (eg. for commands), and the only solution is to either use a static resource (which is only applicable in very few and specific cases), or having to add extra wrapping models just for that, which adds overhead. This is affecting other internal partners as well, and has been broken for years, with no ETA for a fix at all either. I’m pretty sure it’s also broken on WinUI 3 too 😥

noone cares

They said they are working on x:Bind improvements for the 1.6 version of WinAppSdk, let’s hope this will be part of the update.

Also found myself needing this the other day in the Store. I just couldn’t for the love of me get this to work, as the XAML compiler would just refuse to compile code with a binding to something outside of a template, even if visible in XAML. Had to come up with some proxy object to bind to to, as I just couldn’t get a normal binding to the control’s property directly to work.

A fix for this would really, really be welcome 😄

@michael-hawker your latest trick doesn’t work for ItemsRepeater, although it does for ListView/ItemsControl. That is mind blowing! I really want to have at least some workaround, but I can’t, unless I switch from ItemsRepeater to ListView/ItemsControl and only then can switch to use Binding? Crazy! Something is wrong here even with Binding. Please look into it!

Does this not work?

<TextBlock Text="Thanks for entering a valid code!" Visibility="{x:Bind ui:TextBoxExtensions.IsValid(CodeValidator), Mode=OneWay}" /> That should work fine, it’s just a normal binding to function 🤔

IsValid is an attached property not a function. Plus, I would think that it still wouldn’t find the CodeValidator element within the template, as it’s over aggressive about only looking for things on the DataType of the data template.

I mean, yes, but I wanted a statically-typed and reflection-free solution, that’s why x:Bind is cool 😅

Not sure whether this is a regression and if so, when it was introduced, but now I can’t even get the only scenario that was working back when I first opened this issue to work at all anymore. Even just binding to the top viewmodel in a page fails to build. This is a pretty big issue because it blocks many scenarios where you need a backlink to a parent viewmodel for shared functionality (eg. for commands), and the only solution is to either use a static resource (which is only applicable in very few and specific cases), or having to add extra wrapping models just for that, which adds overhead. This is affecting other internal partners as well, and has been broken for years, with no ETA for a fix at all either. I’m pretty sure it’s also broken on WinUI 3 too 😥

Hey all, we’re still heads-down on major feature work/bug fixes for WinUI and Project Reunion, so there likely won’t be any movement on this for several months. Thanks!

Unfortunately, I don’t believe we can investigate this before the official WinUI 3 release in 2021. For your scenario in particular, you could try adding an x:Name to your root UserControl, then x:Bind using the named element (e.g. x:Bind RootUserControl.IsEditing). When looking outside of the namescope it was used in, x:Bind only looks for named elements, and not properties on the root data context.

@jamesc I actually believe this was in fact supported, in particular because VS even has dedicated warnings for this. Like, if your x:DataType model has a property with the same name as the one from code behind, and you x:Bind to it, VS will say something like:

Warning, binding to property will cause the binding to reference the one from the outer scope.

As in, it looks like the system is perfectly aware of the possibility of binding outside of a data template, as @MikeHillberg said. I’d also argue this feature is extremely useful in many cases.

@MikeHillberg is it safe to say then that the issue is just that using anything other than standard x:Bind in this case (eg. function binding, binding from markup extension, etc.) breaks down? But like, that in theory this is a supported scenario that should work? 🤔

This almost looks like it shouldn’t work at all. The DataTemplate has a defined DataType which it uses for its bindings.

I know with old-style Binding, this was possible with ElementName but I think there’s an argument for having this functionality work correctly with x:Bind.

Another drop in the “this would be very useful” ocean.
My case is that without being able to x:Bind outside a DataTemplate, TemplateSelectors become very limiting. A typical usecase is having a TemplateSelector for differnt input types, and if I want to visually affect all of the templates (i.e. disable the actual input element), I have to jump through a lot of ugly hoops (e.g. pushing the visual logic into a “viewmodel” layer).

I would think that it still wouldn’t find the CodeValidator element within the template

Confirmed. x:Bind won’t look for elements inside a DataTemplate.

Does this not work?

<TextBlock
    Text="Thanks for entering a valid code!"
    Visibility="{x:Bind ui:TextBoxExtensions.IsValid(CodeValidator), Mode=OneWay}" />

That should work fine, it’s just a normal binding to function 🤔

Unrelated, but want to call this out: @LeonSpors I’d strongly recommended not to use [INotifyPropertyChanged] and instead to inherit from ObservableObject if you can. I implemented the attribute to help in scenarios where you could not inherit from ObservableObject, eg. if you had to inherit from another type which didn’t have the interface, so you could still get the functionality from it. But if you can, do prefer inheriting from ObservableObject instead, as it’ll reduce code duplication and binary size, as every viwmodel will just share the same implementation of all the helper methods from the base class instead of each carrying its own private copy for no reason 🙂

after change the generated code, it compiles. @RealTommyKlein image

image

@hansmbakker does using {x:Bind ElementName=workaroundNameForControl, Path=IsEditing} work?

{Binding} and ElementName will walk up the element tree at runtime. IIRC x:Bind will statically search up the naming scopes – the DataTemplate then the x:Class.