2014-11-22 53 views
1

請看看這個:數據綁定在XAML的SelectedItem

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" 
      DataContext="{StaticResource vm}"> 
     <Grid.ColumnDefinitions> 
      <ColumnDefinition Width="194*"/> 
      <ColumnDefinition Width="489*"/> 
     </Grid.ColumnDefinitions> 
     <ListView HorizontalAlignment="Left" 
        ItemsSource="{Binding Path=Places}" 
        SelectedItem="{Binding Path=SelectedPlace, Mode=TwoWay}" Margin="0,96,0,0"> 
      <ListView.ItemTemplate> 
       <DataTemplate> 
        <StackPanel Orientation="Horizontal"> 
         <TextBlock Text="{Binding Path=Title}"/> 
        </StackPanel> 
       </DataTemplate> 
      </ListView.ItemTemplate> 
     </ListView> 

     <StackPanel Grid.Column="0" HorizontalAlignment="Left"> 

     <TextBlock 
     VerticalAlignment="Top" 
     Text="{Binding SelectedPlace.Title}" Margin="0,64,0,0"/> 
     </StackPanel> 


    </Grid> 

我在路過的地方名單,其做工精細和列表被顯示在視圖中。問題是selectedItem。智能感知在這裏找到屬性

Text="{Binding SelectedPlace.Title}" 

但它不顯示在視圖中。 當我把一個斷點在我的視圖模型,我可以看到,該值的變化:

public class MainViewModel : ViewModelBase 
    { 
     public ObservableCollection<Place> Places { get; set; } 

     public Place _selectedPlace { get; set; } 

     public Place SelectedPlace 
     { 
      get { return _selectedPlace; } 
      set { _selectedPlace = value; } 
     } 

     public MainViewModel() 
     { 
      Places = new ObservableCollection<Place>() 
      { 
       new Place() {Title = "London", Description = "London is a nice..."}, 
       new Place() {Title = "Dublin", Description = "Dublin is a ...."} 
      }; 
     } 
    } 

有誰知道我缺少什麼?謝謝

回答

1

您需要調用RaisePropertyChanged。

 public Place SelectedPlace 
     { 
      get { return _selectedPlace; } 
      set 
      { _selectedPlace = value; 
       RaisePropertyChanged("SelectedPlace")} 
      } 
     } 

而且你應該也可能初始化此屬性:

public MainViewModel() 
    { 
     Places = new ObservableCollection<Place>() 
     { 
      new Place() {Title = "London", Description = "London is a nice..."}, 
      new Place() {Title = "Dublin", Description = "Dublin is a ...."} 
     }; 
     SelectedPlace = Places[0]; 
    } 

並且通過使SelectedPlace屬性的支持字段私有字段請你幫個忙。你可能想改變它,因爲這:

public Place _selectedPlace { get; set; } 

private Place _selectedPlace; 
+0

完美!謝謝! – Wranglerino 2014-11-22 21:33:01