2012-03-15 141 views
0

对C#和MVVM比较新,但我正在使用MVVM Light Toolkit制作WP7应用程序。我遇到了ListBox中属性的双向绑定问题。我有一个ObservableCollection的客户端,我试图选择一个单独的客户端(点击时会将我带到一个新的ViewModel)。SelectedItem属性没有更新

当我点击一个选定的项目时,它应该更新SelectedItem属性并将该值设置为单击的客户端。然而,点击它甚至没有达到setter(我用*标记了断点)。有谁知道我错了什么地方或有更好的建议解决方案吗?我一直在拖这个地方好几个小时!

XAML标记:

 <ListBox SelectedItem="{Binding SelectedItem, Mode=TwoWay}" ItemsSource="{Binding ClientList, Mode=TwoWay}" x:Name="FirstListBox" Margin="0,0,-12,0" ScrollViewer.VerticalScrollBarVisibility="Auto"> 
     <ListBox.ItemTemplate> 
      <DataTemplate> 
       <StackPanel Margin="0,0,0,17" Width="432"> 
        <Button CommandParameter="{Binding}"> 
         <helper:BindingHelper.Binding> 
          <helper:RelativeSourceBinding Path="ShowClientCommand" TargetProperty="Command" 
            RelativeMode="ParentDataContext" /> 
         </helper:BindingHelper.Binding> 
         <Button.Template> 
          <ControlTemplate> 
           <TextBlock Text="{Binding Name}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" /> 
          </ControlTemplate> 
         </Button.Template> 
        </Button> 
       </StackPanel> 
      </DataTemplate> 
     </ListBox.ItemTemplate> 
    </ListBox> 

视图模型属性:

public ObservableCollection<Client> ClientList 
    { 
     get 
     { 
      return _clientList; 
     } 
     set 
     { 
      _clientList = value; 
      RaisePropertyChanged("ClientList"); 
     } 
    } 

    public Client SelectedItem 
    { 
     get 
     { 
      return _selectedItem; 
     } 
     set 
     { 
     * _selectedItem = value; 
      RaisePropertyChanged("SelectedItem"); 
     } 
    } 
+0

你为什么要使用一个按钮在ListBox模板中?我不确定,但可能SelectedItem不会发生,因为按钮点击事件首先发生! – 2012-03-16 00:14:25

+0

使用按钮跟随了MVVM模式中的列表框教程,这引导了我这样做。你确实是对的! – renegade442 2012-03-16 00:53:40

回答

0

会不会是因为你没有为它是不会改变的属性selection_changed事件签署了?

我不完全确定为什么这不起作用,但这里有一个我总是使用和模板推荐的解决方案。

注册为SelectionChanged事件的列表框起来像这样:

<ListBox SelectionChanged="FirstListBox_SelectionChanged" ItemsSource="{Binding ClientList, Mode=TwoWay}" x:Name="FirstListBox" Margin="0,0,-12,0" ScrollViewer.VerticalScrollBarVisibility="Auto"> 

然后在相应的cs文件,有一个处理程序,看起来像这样:

private void FirstListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    // If selected index is -1 (no selection) do nothing 
    if (FirstListBox.SelectedIndex == -1) 
     return; 

    // get the client that's selected 
    Client client = (Client) FirstListBox.selectedItem; 

    //... do stuff with the client .... 

    // reset the index (note this will fire this event again, but 
    // it'll automatically return because of the first line 
    FirstListBox.SelectedIndex = -1; 
} 
+0

嗯,这个工程,当我拿走我已经实现的按钮逻辑,而是使用selectionChanged。我不得不放弃这种解决方案的MVVM模式,但我会寻找一种方法将它和SelectionChanged事件结合起来。感谢您的回复 - 它让我继续前进。 :) – renegade442 2012-03-16 00:38:08

+0

是的,你发布的代码看起来应该可以工作,并且我对MVVM模式不够了解,所以我只是告诉了你我所知道的工作。但我很高兴你在滚动:) – Nico 2012-03-16 07:16:53

相关问题