จะรับการอ้างอิงของรายการกล่องรายการหลักใน XAML ได้อย่างไร

<Window> <!-- DataContext="HomeViewModel" -->
    <ListBox ItemsSource="{Binding Discs}"> <!-- HomeViewModel.ObservableCollection<DiscViewModel> -->
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TreeView ItemsSource="{Binding Folders}"> <!-- DiscViewModel.IList<Folder> -->
                    <TreeView.ItemTemplate>
                        <DataTemplate>
                            <cc:TreeViewItemEx Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}, Path=DataContext.GetFilesCommand}"/>
                        </DataTemplate>
                    </TreeView.ItemTemplate>
                </TreeView>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Window>

ฉันต้องการดำเนินการ GetFilesCommand (กำหนดโดย DiscViewModel) เมื่อ Folder ถูกขยาย สำหรับสิ่งนี้ ฉันขยาย TreeViewItem ด้วย Command เป็น DependencyProperty และดำเนินการคำสั่งนี้ใน OnExpanded (แทนที่) ใช้งานได้ แต่ Command ถูกตั้งค่าเป็นโมฆะ เหตุผลระบุไว้ด้วยข้อผิดพลาดด้านล่าง:

ไม่พบคุณสมบัติ 'GetFilesCommand' ใน 'วัตถุ' ''HomeViewModel' (HashCode = 22799085)' BindingExpression:Path=DataContext.GetFilesCommand; DataItem='ListBox' (ชื่อ=''); องค์ประกอบเป้าหมายคือ 'TreeViewItemEx' (ชื่อ = ''); คุณสมบัติเป้าหมายคือ 'Command' (พิมพ์ 'ICommand')

ฉันเข้าใจข้อผิดพลาด แต่ไม่รู้วิธีแก้ไข XAML เพื่อให้เลือกคำสั่งจาก DiscViewModel ที่ผูกไว้กับรายการปัจจุบัน


person Nikhil Vartak    schedule 15.07.2018    source แหล่งที่มา


คำตอบ (1)


อ่า แย่แล้ว! ดูเหมือนว่าฉันต้องการอัลมอนด์

เปลี่ยน

AncestorType={x:Type ListBox}}

To

AncestorType={x:Type ListBoxItem}}

ด้วยโค้ดเดิม มันเลือก ListBox's DataContext ขึ้นมา และดังนั้นจึงบ่นเกี่ยวกับคำสั่งที่ไม่พบใน HomeViewModel ซึ่งก็คือ DataContext สำหรับ ListBox

เลือกที่จะไม่ลบคำถาม เพราะมั่นใจว่าอาจมีคนสะดุดปัญหาเดียวกันนี้ในอนาคต

person Nikhil Vartak    schedule 15.07.2018