【发布时间】:2014-04-23 11:50:27
【问题描述】:
我想从视图模型中选择列表框项?
我的 xaml 是:-
<Grid x:Name="MVVMListBoxUIContainer" Grid.Row="1" Margin="2,0,2,0">
<ListBox Height="374" ItemsSource="{Binding StudentDetails,Mode=TwoWay}" HorizontalAlignment="Left" Margin="2,6,0,0" Name="listBox1" VerticalAlignment="Top" Width="476" BorderBrush="#00410D0D">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Tap">
<i:InvokeCommandAction Command="{Binding EventPageCommand, Mode=OneWay}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Gray" Padding="5" BorderThickness="1">
<StackPanel Orientation="Horizontal">
<Border BorderBrush="Wheat" BorderThickness="1">
<Image Name="ListPersonImage" Source="{Binding PersonImage}" Height="100" Width="100" Stretch="Uniform" Margin="10,0,0,0"/>
</Border>
<TextBlock Text="{Binding FirstName}" Name="firstName" Width="200" Foreground="White" Margin="10,10,0,0" FontWeight="SemiBold" FontSize="22" />
<Button Margin="-100,0,0,0" Height="80" Width="80" DataContext="{Binding DataContext, ElementName=listBox1}" Command="{Binding addPerson}">
<Button.Background>
<ImageBrush ImageSource="{Binding addImage}" Stretch="Fill" />
</Button.Background>
</Button>
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我的视图模型:-
EventPageCommand = new ReactiveAsyncCommand();
EventPageCommand.Subscribe(x =>
{
MessageBox.Show("List box item is clicked.");
});
在这里,当我单击列表框项目时,消息框正在显示。但我无法显示所选项目。 但我可以从 Xaml.CS 显示。
private void listBox1_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
ListBox listbox = (ListBox)sender;
ListBoxEventsModel items = (ListBoxEventsModel)listbox.SelectedItem;
MessageBox.Show("Selected Name"+items.FirstName);
//if(!Constants.buttonSelected)
//MessageBox.Show("List item is selected..!!");
}
但是当我从视图模型中尝试时,我无法显示所选项目。请让我知道如何显示所选项目。 我试过这样:-
EventPageCommand = new ReactiveAsyncCommand();
EventPageCommand.Subscribe(x =>
{
MessageBox.Show("List box item is clicked.");
ListBox listbox = (ListBox)sender;
ListBoxEventsModel items = (ListBoxEventsModel)listbox.SelectedItem;
MessageBox.Show("Selected Name" + items.FirstName);
});
但我收到此错误:- 名称“发件人”在当前上下文中不存在
【问题讨论】:
-
您必须在 ListBox 中使用参数 Mode=TwoWay 绑定 SelectedItems
-
嗨@Musketyr。谢谢您的回复。我是 Windows 手机的新手。你能给我举个例子吗(对不起)?
标签: c# windows-phone-7 mvvm listbox reactiveui