Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot bind to button events using x:Bind in DataTemplates - generates XAML error

With the {x:Bind} markup syntax you can bind to events provided the method meets the following requirements:

  • Match the signature of the event.
  • OR have no parameters.
  • OR have the same number of parameters of types that are assignable from the types of the event parameters.

This works perfectly fine outside of a DataTemplate. Once the binding happens inside the DataTemplate the compiler generates the following error:

Xaml Internal Error error WMC9999: Object reference not set to an instance of an object.

What is the fix for binding to events inside DataTemplates?

Full example code here.

Snippet of the example code below - note the first button (line 2) is fine and the second button (line 6) is also fine. If you comment out line 6 and and comment in line 7, the error occurs.

 <StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Button Tapped="{x:Bind Click}" Content="WORKING"/>
        <ListView ItemsSource="{x:Bind Names}">
            <ListView.ItemTemplate>
                <DataTemplate x:DataType="local:Customer"> 
                    <Button Content="{x:Bind Title}"/>
                    <!--<Button Tapped="{x:Bind Clicky}" Content="{x:Bind Title}"/>-->
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackPanel>
like image 915
Robert MacLean Avatar asked Feb 14 '26 00:02

Robert MacLean


1 Answers

I was able to get it to work with the following code:

<DataTemplate x:DataType="local:Customer">
     <StackPanel Orientation="Vertical">
         <Button Tapped="{x:Bind Clicky}" Content="{x:Bind Title}" />
     </StackPanel>
</DataTemplate>

It seems as though you need to have it inside a container for it work. I have no idea why I am guessing magic.

like image 111
davemsdevsa Avatar answered Feb 17 '26 02:02

davemsdevsa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!