Skip to content

Document DataContext type inference. #736

@pixsperdavid

Description

@pixsperdavid

Is your feature request related to a problem? Please describe.

Currently, binding to the data context of a parent control requires a verbose syntax including a cast. E.g. from the Avalonia docs:

<ItemsRepeater ItemsSource="{Binding MyItems}">
<ItemsRepeater.ItemTemplate>
    <DataTemplate>
    <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding DisplayName}"/>
        <Grid>
        <Button Command="{Binding $parent[ItemsRepeater].((vm:MyUserControlViewModel)DataContext).DoItCommand}"
                CommandParameter="{Binding ItemId}"/>
        </Grid>
    </StackPanel>
    </DataTemplate>
</ItemsRepeater.ItemTemplate>
</ItemsRepeater>

The {Binding $parent[ItemsRepeater].((vm:MyUserControlViewModel)DataContext).DoItCommand} in the above example is tricky to get right (personally I still constantly get the casting syntax wrong) and hostile to new users for what is a very common scenario. Additionally the syntax currently requires the import of an additional XAML namespace in order to specify the type cast when this could otherwise be inferred.

Describe the solution you'd like

The simplest solution would be to automatically infer the parent data context's type when resolving the binding.

Another possibility could be the introduce a new binding syntax along the lines of $parentDataContext which infers the type.

Describe alternatives you've considered

No response

Additional context

I'm willing to look at implementation of either the above solutions, or any other suggested way of improving this pain point.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions