Search code examples
c#wpfbindingrelativesource

Error Using RelativeSource FindAncestor in WPF


I do have an Window (DataContext VM) and a Listview (ItemSource Observable List in VM) Data comes from an sqlite DB, the Observable List is Type of Model, representing Residents. Each Resident should have an "CheckIn" or "CheckOut" Button, for them, i do have ICommands in my VM.

<ListView ItemsSource="{Binding Oc_BewohnerList}">
                        <ListView.ItemTemplate>
                            <DataTemplate>
                                <WrapPanel>
                                    <TextBlock Text="Name:" Width="50"/>
                                    <TextBlock Text="{Binding Nachname, StringFormat={}{0}\, }" FontWeight="Bold"/>
                                    <Button Content="Check In" Command="{Binding Source={RelativeSource AncestorType={x:Type viewModels:BewohnerVM}}, Path=CheckInCommand}" CommandParameter="{Binding Id}" />

Why do i get an Error "Die Eigenschaft "CheckInCommand" wurde im Objekt vom Typ "RelativeSource" nicht gefunden." That the CheckInCommand is not found?

I did it first with Xamarin.Forms and there it worked in a similiar way ... i cant find a solution myself, tried tons of combinations for realtivesource and ancestorlevel ...

Thx in advance Nala


Solution

  • Likely just a small syntax error and you want (note the double usage of RelativeSource , once as a property of Binding once as MarkupExtension...)

    EDIT and also the AncestorType should be an UIElement, whose DataContext exposes that CheckInCommand.

    <Button Content="Check In" 
         Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListView}}, Path=DataContext.(viewModels:BewohnerVM.CheckInCommand)}"
         CommandParameter="{Binding Id}" />