简体   繁体   中英

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

A relativesource binding is up the visual tree. As in controls not viewmodels. You're not going to be looking for a viewmodel. If the command is a property on VM and that's the datacontext of the window then the ListView inherits that datacontext.

You've not explained everything but I think you need more like:

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

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}" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM