2010-03-17 140 views
1

下面的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有關的問題?

回答

4

簡短的回答

更換

SelectedValuePath="{Binding /Length}" 

SelectedValuePath="Length" 

龍答案

SelectedValuePath是一個字符串,給出了PA從一個對象到選定的值。通過編寫SelectedValuePath="{Binding /Length}"SelectedValuePath(不SeletedValue)結合所選項目的「長度」屬性,因此,如果所選項目的長度爲3,那麼SelectedValuePath屬性的值設置爲字符串「3」。然後,WPF嘗試通過查找字符串上名爲「3」的屬性來計算SelectedValue。由於字符串對象沒有名爲「3」的屬性,因此會出現錯誤。

你可能會認爲SelectedValue={Binding /Length}"會做的伎倆,實際上它表達的是什麼,你實際上是試圖做的概念。但它並不實際工作,因爲Selector的代碼會在SelectedItem更改時覆蓋SelectedValue

另一種方式來看待這個是設置SelecteValuePath值「ABCD」實際上等同於設置SelectedValue"{Binding /abcd}"(但只有當IsSynchronizedWithCurrentItem =「真」)。