簡體   English   中英

綁定命令-祖先

[英]Binding command - Ancestor

好的,伙計們 我已經嘗試了大約3天,並且沒有任何Google搜索可以提供幫助。 以下是我的XAML的摘要(應該足夠了)。 我的問題是“ ContextMenu”的命令。 如您所見,我具有DeleteTagCommand 現在,如果我將它放在CheckBoxCommand的位置,該命令就可以使用,這很棒。.但是,它將在當前位置被調用,這讓我發瘋。

        <ScrollViewer Grid.Column="0">
            <StackPanel Orientation="Vertical">
                <ItemsControl ItemsSource="{Binding Tags, UpdateSourceTrigger=PropertyChanged}">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <CheckBox Content="{Binding Value}" Margin="10,5,10,5" Command="{Binding DataContext.CheckBoxCommand,
                                                                                           RelativeSource={RelativeSource FindAncestor,
                                                                                           AncestorType={x:Type Grid}}}"
                                  CommandParameter="{Binding }">
                                <CheckBox.ContextMenu>
                                    <ContextMenu>
                                        <MenuItem Header="Delete" Command="{Binding DataContext.DeleteTagCommand,
                                                                                    RelativeSource={RelativeSource FindAncestor,
                                                                                    AncestorType={x:Type Grid}}}"
                                                  CommandParameter="{Binding}" />
                                    </ContextMenu>
                                </CheckBox.ContextMenu>
                            </CheckBox>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </StackPanel>
        </ScrollViewer>

我試過了:

  • 在整個演出中都在調用“ ElementName”,但從未被使用
  • 將“ AncestorLevel”更改為淫穢數字,希望這是問題所在
  • 和更多..

不知道什么對你們有用,但是下面是我得到的輸出消息

找不到參考'RelativeSource FindAncestor,AncestorType ='System.Windows.Controls.Grid',AncestorLevel ='1''的綁定源。 BindingExpression:Path = DataContext.DeleteTagCommand; DataItem = null; 目標元素是'MenuItem'(Name =''); 目標屬性為“命令”(類型為“ ICommand”)

謝謝

ContextMenu實際上與其父級不在同一視覺樹中,因此它們無法直接綁定到其中的任何元素。 但是,它們仍然可以綁定到StaticResources。 因此,訣竅是使用中間代理,如本頁上所示BindingProxy類 首先將一個實例添加到ItemsControl資源塊中:

<ItemsControl.Resources>
    <local:BindingProxy x:Key="Proxy" Data="{Binding}" />
</ItemsControl.Resources>

然后使用它來綁定您的ContextMenu命令:

<ContextMenu>
    <MenuItem Header="Delete" Command="{Binding Data.DeleteTagCommand, Source={StaticResource Proxy}}" CommandParameter="{Binding}" />
</ContextMenu>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM