对C#和MVVM比较陌生,但我正在使用MVVM Light Toolkit制作WP7应用程序。我遇到了ListBox中属性的双向绑定问题。我有一个ObservableCollection的客户端,我正在尝试选择一个单独的客户端(点击后会将我带到一个新的ViewModel)。
当我点击所选项目时,它应该更新SelectedItem属性并将值设置为单击的客户端。然而,当点击它甚至没有到达setter(我用*标记了断点)。有谁知道我哪里出错或者有更好的建议解决方案?我拖网几个小时了!
XAML MarkUp:
<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>
ViewModel属性:
public ObservableCollection<Client> ClientList
{
get
{
return _clientList;
}
set
{
_clientList = value;
RaisePropertyChanged("ClientList");
}
}
public Client SelectedItem
{
get
{
return _selectedItem;
}
set
{
* _selectedItem = value;
RaisePropertyChanged("SelectedItem");
}
}
答案 0 :(得分: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;
}