【问题标题】:What path should I write in the binding?我应该在绑定中写什么路径?
【发布时间】:2018-02-23 15:50:19
【问题描述】:

我有一个带有树视图的 WPF 应用程序。有一个分层的项目模板。

我想将图像源绑定到我作为 TreeViewItem 使用的数据类,即 RestoreItemVM。我需要在路径中写什么???到目前为止,我尝试的所有操作都在我的转换器中抛出了一个错误,说它无法将其转换为 RestoreItemVM ...

<TreeView.ItemTemplate>
    <HierarchicalDataTemplate ItemsSource="{Binding Children}" DataType="restoreTab:RestoreItemVM">
        <DockPanel VerticalAlignment="Center" HorizontalAlignment="Left" LastChildFill="False">
            <CheckBox Focusable="False" VerticalAlignment="Center" IsChecked="{Binding IsChecked}" PreviewMouseRightButtonDown="TreeViewItem_OnPreviewMouseRightButtonDown"/>
            <Image Width="20" Margin="3" 
                   Source="{Binding RelativeSource={RelativeSource 
                            FindAncestor, AncestorType={x:Type TreeViewItem}, 
                            AncestorLevel=2}, Converter={x:Static local:RestoreItemToImageConverter.Instance}, 
                            Path= ????? }"  
                   PreviewMouseRightButtonDown = "TreeViewItem_OnPreviewMouseRightButtonDown"/>
       </DockPanel>
    </HierarchicalDataTemplate>
</TreeView.ItemTemplate>

【问题讨论】:

    标签: c# wpf mvvm binding relativesource


    【解决方案1】:

    您需要指定数据上下文的路径:

    Source="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type TreeViewItem}}, Converter={x:Static local:RestoreItemToImageConverter.Instance}, 
             Path=DataContext}"
    

    但实际上,它更简单,因为RestoreItemVM已经是Image的DataContext,你不需要找到它的祖先。试试这个:

    <Image ... Source="{Binding Path=., Converter={x:Static local:RestoreItemToImageConverter.Instance}}" />
    

    Path=. 绑定到 DataContext 本身:

    Special symbols in WPF binding - what does "{Binding Path=.}" mean?

    HierarchicalDataTemplate中的DockPanel中的DataContext就是ItemsSource中的当前RestoreItemVM对象。

    【讨论】:

    • 嗯..这确实有效。你能在我接受之前添加更多解释吗?比如 Path=.是什么意思?
    • 路径=。表示绑定到 DataContext 本身:stackoverflow.com/questions/1066262/…
    • 我添加了更多信息。请批准,我会接受
    • 为了增加一些精度,Path=.(或者只是省略 Path,因为 . 是默认值)意味着直接绑定到 Binding 的当前源对象。根据实际设置源的方式,它可以是当前的 DataContent,也可以是 Binding 的 Source、RelativeSource 或 ElementName 属性所引用的对象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    • 2012-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多