【发布时间】:2011-04-16 23:17:05
【问题描述】:
我有一个 TreeView,它的数据上下文是使用设置的
LayoutRoot.DataContext = value
来自代码隐藏。
CommandTreeViewModel 的 Commands 属性为 IEnumerable(Of CommandViewModel)
CommandViewModel 又拥有多个CommandViewModel 的子代
在我的 XAML 中,我使用以下 XAML 将其转换为树项目
<TreeView ItemsSource="{Binding}"
DataContext="{Binding FirstGeneration}"
x:Name="CommandTreeView">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<Border BorderThickness="1"
Width="200"
Margin="2"
CornerRadius="10,0,10,0">
<StackPanel Orientation="Horizontal"
<Image Source="{Binding Icon}"
Width="24"
Height="24" />
<TextBlock VerticalAlignment="Center"
FontSize="13"
Margin="10,0,0,0"
Text="{Binding Name}"
Foreground="White" />
</StackPanel>
</Border>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
现在我在其他地方有一个图像和两个文本块,我想将它们绑定到所选树视图项的原始数据源上的元素 - 具体来说,Icon、Description、Name。我正在尝试如下所示绑定它们:
<StackPanel Orientation="Vertical"
DataContext="{Binding ElementName=CommandTreeView, Path=SelectedItem}">
<Image x:Name="CommandIcon"
Width="64"
Height="64"
Source="{Binding XPath=@Icon}"></Image>
</StackPanel>
与 TextBlocks 的 Text 属性相同。
当我单击树视图项时,在输出窗口中出现以下异常...
System.Windows.Data Error: 44 : BindingExpression with XPath cannot bind to non-XML object.; XPath='@Icon' BindingExpression:Path=/InnerText; DataItem='CommandViewModel' (HashCode=39320280); target element is 'Image' (Name='CommandIcon'); target property is 'Source' (type 'ImageSource') CommandViewModel:'BitBox.Core.CommandViewModel'
System.Windows.Data Error: 44 : BindingExpression with XPath cannot bind to non-XML object.; XPath='@Name' BindingExpression:Path=/InnerText; DataItem='CommandViewModel' (HashCode=39320280); target element is 'TextBlock' (Name='CommandTitle'); target property is 'Text' (type 'String') CommandViewModel:'BitBox.Core.CommandViewModel'
System.Windows.Data Error: 44 : BindingExpression with XPath cannot bind to non-XML object.; XPath='@Description' BindingExpression:Path=/InnerText; DataItem='CommandViewModel' (HashCode=39320280); target element is 'TextBlock' (Name='CommandBody'); target property is 'Text' (type 'String') CommandViewModel:'BitBox.Core.CommandViewModel'
【问题讨论】: