webdad3
webdad3

Reputation: 9080

ListView SelectItem Binding not working as expected

I have a fairly straight forward listview control for my Windows 8 XAML/C# application. I am binding the listview to a PersonList and that works correctly. However, what I'd like to do and haven't been able to find the answer for is I want the to click an item in the listview and be able to display the PersonSingle object to the other textboxes on the screen.

I've read some posts that indicate that the listview may not be the right control for this operation. Am I missing something in my listview that would allow me to do this operation or should I use a different control?

           <ListView
                x:Name="itemListView"
                Visibility="Visible"
                Width="auto"
                Height="auto"
                ItemsSource="{Binding PersonList, Mode=TwoWay}"
                SelectedItem = "{Binding PersonSingle, Mode=OneWay}"            
                ItemTemplate="{StaticResource person80Template}"
                SelectionMode="Single"
                Grid.Row="1"
                Grid.Column="1"
                VerticalAlignment="Stretch">

                <ListView.GroupStyle>
                    <GroupStyle>
                        <GroupStyle.HeaderTemplate>
                            <DataTemplate>
                                <Grid Margin="7,7,0,0">
                                    <Button
                                AutomationProperties.Name="PersonValue"
                                Content="{Binding PersonName}"
                                Style="{StaticResource TextButtonStyle}"/>
                                </Grid>
                            </DataTemplate>
                        </GroupStyle.HeaderTemplate>
                    </GroupStyle>
                </ListView.GroupStyle>
            </ListView> 

UPDATE:

So I figured out how to do it in a non-MVVM way (or at least not in a true MVVM way)

I added an ItemClick event to my ListView:

ItemClick="itemListView_ItemClick"

And then in the code behind I added the following:

    private void itemListView_ItemClick(object sender, ItemClickEventArgs e)
    {
        VM.PersonSingle = ((Person)e.ClickedItem);
    }

That works, but like I said, it doesn't feel very MVVM'ish. If you have any suggestions on how to make it work without having to manually set the PersonSingle object please answer below.

Upvotes: 0

Views: 55

Answers (1)

Filip Skakun
Filip Skakun

Reputation: 31724

Your ItemClick solution is the right solution. You could create an attached behavior if you are opposed to handling events, but that's your choice.

Upvotes: 1

Related Questions