3
votes

I am using MVVM and I have a listview which is binded to a dictionary in my viewmodel. In my xaml, I've set up the selecteditem to set the correct selected item but unfortunately what I'm doing doesnt work. If I change it to selectedindex with the property datatype changed to int, I'm able to set it. Here's my view.

View(xaml)

<Grid Width="auto" Grid.Column="0" Grid.Row="1" HorizontalAlignment="Left" Margin="0,1,0,0">
    <Grid.RowDefinitions>
        <RowDefinition Height="auto"></RowDefinition>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="188"></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <ListView Name="lstNewPatient" HorizontalAlignment="Left" VerticalAlignment="Bottom" 
         Height="auto" Margin="0,0,0,0" ItemsSource="{Binding Path=TestList}" SelectedItem="{Binding Path=SelectedTestItem}" 
         FontSize="11" SelectionMode="Single">
        <ListView.View>
            <GridView>
                <GridView.ColumnHeaderContainerStyle>
                    <Style>
                        <Setter Property="FrameworkElement.Visibility" Value="Collapsed"/>
                    </Style>
                </GridView.ColumnHeaderContainerStyle>
                <GridViewColumn Width="69" DisplayMemberBinding="{Binding Key}"></GridViewColumn>
                <GridViewColumn Width="109" DisplayMemberBinding="{Binding Value}"></GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>
</Grid>

ViewModel

Dictionary<int, string> selectedTestItem= null;
public Dictionary<int, string> SelectedTestItem
{
    get 
    { 
        return selectedTestItem; 
    }
    set
    {
        selectedTestItem = value;
        OnPropertyChanged("SelectedTestItem");
    }
}

private Dictionary<int, string> TestList()
{
    var newTestList = new Dictionary<int, string>();

    newTestList.Add(1, "Apple");
    newTestList.Add(2, "Car");
    newTestList.Add(3, "Laptop");


    return newPtLevelList;
}
1

1 Answers

6
votes

SelectedTestItem should be KeyValuePair<int, string>, not Dictionary<int, string>