下面的XAML的生產運行時綁定錯誤,當我在ListBox
單擊一個項目:試圖更好地瞭解SelectedValuePath和IsSynchronizedWithCurrentItem
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="WpfApplication1.MainWindow"
x:Name="Window"
Title="MainWindow"
Width="640" Height="480">
<Window.Resources>
<x:Array x:Key="strings" Type="{x:Type sys:String}">
<sys:String>one</sys:String>
<sys:String>two</sys:String>
<sys:String>three</sys:String>
<sys:String>four</sys:String>
</x:Array>
</Window.Resources>
<Grid>
<ListBox
DataContext="{StaticResource strings}"
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding}"
SelectedValuePath="{Binding /Length}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.Resources>
<Style TargetType="{x:Type Label}">
<Setter Property="Background" Value="Yellow"/>
<Setter Property="Margin" Value="0,0,4,0"/>
<Setter Property="Padding" Value="0"/>
</Style>
</Grid.Resources>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<!-- Row 0 -->
<Label Grid.Column="0" Grid.Row="0">String:</Label>
<TextBlock
Grid.Column="1"
Grid.Row="0"
Text="{Binding}"/>
<!-- Row 1 -->
<Label Grid.Column="0" Grid.Row="1">Length:</Label>
<TextBlock
Grid.Column="1"
Grid.Row="1"
Text="{Binding Length, Mode=Default}"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
這是運行時綁定的錯誤信息:
System.Windows.Data Error: 39 : BindingExpression path error: '3' property not found on 'object' ''String' (HashCode=1191344027)'. BindingExpression:Path=3; DataItem='String' (HashCode=1191344027); target element is 'ListBox' (Name=''); target property is 'NoTarget' (type 'Object')
我想ListBox
的所選值爲選定對象String
的長度。我的SelectedValuePath
綁定語法有什麼問題?有沒有與IsSynchronizedWithCurrentItem
有關的問題?