Search code examples
c#mvvmreactiveuiavaloniaui

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/


Solution

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