MVVM listview绑定到字典selecteditem问题

时间:2012-10-26 18:30:26

标签: c# wpf listview

我正在使用MVVM,我有一个listview,它绑定到我的viewmodel中的字典。在我的xaml中,我已经设置了selecteditem以设置正确的选定项目但不幸的是我正在做的事情不起作用。如果我将属性数据类型更改为int,将其更改为selectedindex,我可以设置它。这是我的观点。

查看(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>

视图模型

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 个答案:

答案 0 :(得分:6)

SelectedTestItem应该是KeyValuePair<int, string>,而不是Dictionary<int, string>