Listview SelectedItem不绑定

时间:2019-07-24 05:51:53

标签: c# wpf listview

我遇到一个问题,尝试使用Listview显示对象列表并将其发送到新页面。但是,BrandBox.isSelected返回null。

.xaml

     <Grid >
        <ListView x:Name="BrandBox" HorizontalAlignment="Stretch" VerticalAlignment="Top" SelectedItem="{Binding ItemSelected, Mode=TwoWay}" SelectionChanged="Selector_OnSelectionChanged">
            <ListView.View>
                <GridView>
                    <GridViewColumn>
                        <GridViewColumn.CellTemplate >
                            <DataTemplate>
                                <StackPanel Orientation="Vertical" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Width="128">
                                    <Image Source="{Binding BrandImageLoc}" HorizontalAlignment="Stretch" VerticalAlignment="Top" Stretch="UniformToFill" />
                                    <TextBlock Text="{Binding BrandName}" HorizontalAlignment="Stretch" VerticalAlignment="Bottom" />
                                </StackPanel>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>

.cs

        List<Brand> Brands = new List<Brand>();

        public ManufactuerList()
        {
            InitializeComponent();

            Brands = App.career.Brands;
            this.BrandBox.ItemsSource = Brands;

        }

        private void Selector_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Brand selectedBrand = BrandBox.SelectedItem as Brand;
            this.NavigationService.Navigate(new CarsPurchaseable(selectedBrand));
        }

1 个答案:

答案 0 :(得分:0)

尝试这样做

 private void Selector_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
 {
     ListView brandBox = sender as ListView;
    if(brandBox != null)
    {
        Brand selectedBrand = brandBox.SelectedItem as Brand;
        if(selectedBrand != null)
        {
            this.NavigationService.Navigate(new CarsPurchaseable(selectedBrand));
        }
    }
}