AndyPrince
AndyPrince

Reputation: 83

Binding to a MainViewModel command from an ItemsControl Button in Avalonia

I am trying to create a ReactiveUI MVVM binding from an ItemsControl Button in Avalonia In WPF this would be done via a Freezable BindingProxy. However, it looks like Freezable isn't available in Avalonia. How should such a binding be created?

            <ItemsControl Items="{Binding MyQueue}">
              <ItemsControl.ItemTemplate>
                <DataTemplate>
                  <Button Content="My Button"
                          HorizontalAlignment="Center" VerticalAlignment="Center"
                          CommandParameter="{Binding}"
                          Command="{Binding MySpecialCmd}"/>
                </DataTemplate>
              </ItemsControl.ItemTemplate>
            </ItemsControl>

References:
https://stackoverflow.com/questions/22073740/binding-visibility-for-datagridcolumn-in-wpf\ https://thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/

Upvotes: 2

Views: 2865

Answers (3)

Hellong
Hellong

Reputation: 41

For those who tried the answer of @AndyPrince but got served with an error of the type

Unable to resolve property or method of name 'MySpecialCmd' on type 'System.Object'

This is caused by the compiled bindings being unable to know the real type of the datacontext. However, there is a workaround by casting :

Command="{Binding $parent[ItemsControl].((vm:MyViewModel)DataContext).MySpecialCmd}"

Upvotes: 2

Flictivity
Flictivity

Reputation: 11

In Avalonia version 11.0.0 need off CompileBinding param.

x:CompileBindings="False"

Upvotes: 1

AndyPrince
AndyPrince

Reputation: 83

Big thanks to @maxkatz6 on the AvaloniaUI gitter. Here is the solution:

{Binding $parent[ItemsControl].DataContext.MySpecialCmd}
           <ItemsControl Items="{Binding MyQueue}">
              <ItemsControl.ItemTemplate>
                <DataTemplate>
                  <Button Content="My Button"
                          HorizontalAlignment="Center" VerticalAlignment="Center"
                          CommandParameter="{Binding}"
                          Command="{Binding $parent[ItemsControl].DataContext.MySpecialCmd}"/>
                </DataTemplate>
              </ItemsControl.ItemTemplate>
            </ItemsControl>

Upvotes: 6

Related Questions