Как выбрать элементы списка из модели представления

Я хочу выбрать элементы списка из модели представления?

Мой 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);
});

Но я получаю сообщение об ошибке: Имя отправителя не существует в текущем контексте


person Vijay    schedule 23.04.2014    source источник
comment
Вы должны привязать SelectedItems в ListBox с параметром Mode=TwoWay   -  person Musketyr    schedule 23.04.2014
comment
Привет @Мушкетир. Спасибо за ответ. Я новичок в Windows Phone. Можете ли вы привести какой-либо пример для меня (извините)?   -  person Vijay    schedule 23.04.2014


Ответы (1)


В xaml в ListBox:

SelectedItem={Binding SelectedStudent, Mode=TwoWay}

Затем в ViewModel:

public ObservableCollection<YOUR_OBJECT_HERE> SelectedItems { get; set;}

EDIT Полный пример:

 <ListBox Margin="5,0" Grid.Row="1" Grid.RowSpan="2" ItemsSource="{Binding Roles}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Path=Title}" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

ViewModel

public class RolesViewModel : BaseViewModel
{
    private Collection<BO.RoleBO> roles;
    private BO.RoleBO selectedItem;

    public BO.RoleBO SelectedItem
    {
        get { return selectedItem; }
        set 
        { 
            selectedItem = value;
            NotifyOnPropertyChanged("SelectedItem"); 
        }
    }

    public Collection<BO.RoleBO> Roles
    {
        get { return roles; }
        set { roles = value; NotifyOnPropertyChanged("Roles"); }
    }

}
person Musketyr    schedule 23.04.2014
comment
Привет .. Я попробовал вашу идею. Но не работает.. public static ObservableCollection‹MVVMListBoxModel› _SelectedStudent; public ObservableCollection‹MVVMListBoxModel› SelectedStudent { get { return _SelectedStudent; } set { this.RaiseAndSetIfChanged(x => x.SelectedStudent, значение); MessageBox.Show(Выбрано); } - person Vijay; 23.04.2014
comment
Вы вызвали конструктор: new ObservableCollection...? - person Musketyr; 23.04.2014
comment
Привет @Мушкетир. Нет простите. Пожалуйста, приведите мне пример? - person Vijay; 23.04.2014
comment
Используйте stackoverflow.com/questions/8692969/ - person Dhaval Patel; 23.04.2014
comment
Привет @Dhaval.. Это то, что я хочу.. Спасибо..!! - person Vijay; 25.04.2014
comment
Привет @Musketyr.. Спасибо за ваши советы.. Работает gr8..!! - person Vijay; 25.04.2014