简体   繁体   English

使用 mvvm 和 c# 获取选定行数的正确方法是什么?

[英]What is the correct way to get the selected rows count using mvvm and c#?

In my WPF app I have a datagrid like在我的 WPF 应用程序中,我有一个数据网格

<DataGrid
                SelectedItem="{Binding SelItm, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                ItemsSource="{Binding FilteredStudents}"
                SelectionMode="Extended"
                AutoGenerateColumns="False"
                IsReadOnly="True"
                SelectionUnit="FullRow"
                HeadersVisibility="Column"
                <DataGrid.Columns>
                    <DataGridTextColumn
                        Header="Bill No."
                        Binding="{Binding Path=Name, Mode=OneWay}"
                        Width="260"
                        IsReadOnly="True" />
                    <DataGridTextColumn
                        Header="Bill Date"
                        Binding="{Binding Path=Address, Mode=OneWay}"
                        Width="200"
                        IsReadOnly="True" />
                    <DataGridTextColumn
                        Header="Amount"
                        Binding="{Binding Path=Age, Mode=OneWay}"
                        Width="210"
                        IsReadOnly="True" />
                </DataGrid.Columns>
            </DataGrid>

The itemsource of the datagrid is an ICollectionView called FilteredStudents .数据网格的项目源是一个名为FilteredStudentsICollectionView I've created a property selrows in my viewmodel which I binded to a label to display the selected rows count using like selrows = SelItm.Count();我在我的视图模型中创建了一个属性selrows ,我将其绑定到 label 以使用 like selrows = SelItm.Count();显示选定的行数。 . .

    private ICollectionView _allFilteredStudents;
    public ICollectionView FilteredStudents
    {
        get
        {
            if(_allFilteredStudents == null)
            {
                this._allFilteredStudents = new ListCollectionView(GetAllStudents)
                {
                    Filter = o => ((Students)o).Name != "Ram"
                };
            }
            return _allFilteredStudents;
        }
    }

But it is displaying incorrect result.但它显示的结果不正确。

BTW, my database looks like顺便说一句,我的数据库看起来像

在此处输入图像描述

What is the proper way to get the selected rows count of a WPF datagrid following mvvm pattern?按照 mvvm 模式获取 WPF 数据网格的选定行数的正确方法是什么?

Here is the solution:这是解决方案:

If you are going to show the number of the selected row in the view, simply choose a name for the grid and bind to SelectedItems.Count of the grid.如果您要在视图中显示所选行的编号,只需为网格选择一个名称并绑定到网格的SelectedItems.Count

In order to access selected items count in your c# code, you can add a IsSelected property to the StudentModel and bind it to the row's IsSelected attribute using RowStyle .为了访问 c# 代码中的选定项目计数,您可以将IsSelected属性添加到StudentModel并使用RowStyle将其绑定到行的IsSelected属性。 This way whenever a row is selected/unselected, the IsSelected property of the StudentModel will be updated in the code and you can find selected students using that proertry like this FilteredStudents.Cast<StudentModel>().Count(i => i.IsSelected) This way whenever a row is selected/unselected, the IsSelected property of the StudentModel will be updated in the code and you can find selected students using that proertry like this FilteredStudents.Cast<StudentModel>().Count(i => i.IsSelected)

<Grid>
     <Grid.RowDefinitions>
        <RowDefinition Height="auto"/>
        <RowDefinition Height="auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Button Content="GetSelectedRowsCount" Command="{Binding ButtonCommand}"/>
    <TextBlock Grid.Row="1" Text="{Binding ElementName=grid, Path=SelectedItems.Count}"/>
    <DataGrid Grid.Row="2" x:Name="grid"
            ItemsSource="{Binding FilteredStudents}"
            SelectionMode="Extended"
            AutoGenerateColumns="False"
            IsReadOnly="True"
            SelectionUnit="FullRow"
            HeadersVisibility="Column" >
        <DataGrid.RowStyle>
            <Style TargetType="DataGridRow">
                <Setter Property="IsSelected" Value="{Binding Path = IsSelected}"/>
            </Style>
        </DataGrid.RowStyle>
        <DataGrid.Columns>
            <DataGridTextColumn Header="Id" Binding="{Binding Path=Id, Mode=OneWay}"/>
            <DataGridTextColumn Header="Name" Binding="{Binding Path=Name, Mode=OneWay}"/>
        </DataGrid.Columns>
    </DataGrid>
</Grid>

Now there is a IsSelected property in your StudentModel you can find how many rows are selected by filtering the collection in your code.现在您的StudentModel中有一个IsSelected属性,您可以通过在代码中过滤集合来查找选择了多少行。

Here is the student model:这是学生 model:

public class StudentModel : Notifier
{
    private int _id;
    public int Id
    {
        get { return _id; }
        set
        {
            this._id = value;
            RaisePropertyChanged();
        }
    }

    private string _name;
    public string Name
    {
        get { return _name; }
        set
        {
            this._name = value;
            RaisePropertyChanged();
        }
    }

    private bool _isSelected;
    public bool IsSelected
    {
        get { return _isSelected; }
        set
        {
            this._isSelected = value;
            RaisePropertyChanged();
        }
    }
}

and this is the viewModel:这是视图模型:

public class AppPresenter : Notifier
{
    private ICollectionView _allFilteredStudents;
    public ICollectionView FilteredStudents
    {
        get
        {
            if (_allFilteredStudents == null)
            {
                this._allFilteredStudents = new ListCollectionView(GetAllStudents())
                {
                    Filter = o => ((StudentModel)o).Name != "Ram"
                };
            }
            return _allFilteredStudents;
        }
    }

    public List<StudentModel> GetAllStudents()
    {
        return new List<StudentModel>()
        {
            new StudentModel(){ Id=1, Name="name1"},
            new StudentModel(){ Id=2, Name="name2"},
            new StudentModel(){ Id=3, Name="name3"},
            new StudentModel(){ Id=4, Name="name4"},
        };
    }


public int GetSelectedRowCount()
{
    var selrows = FilteredStudents.Cast<StudentModel>().Count(i => i.IsSelected);

    return selrows;
}


private RelayCommand _buttonCommand;

public RelayCommand ButtonCommand
{
    get
    {
        if (_buttonCommand == null)
        {
            _buttonCommand = new RelayCommand(param => this.GetSelectedRowCount());
        }

        return _buttonCommand;
    }
}
     
}

Finally this is the MainWindow.cs最后这是MainWindow.cs

public MainWindow()
{
    InitializeComponent();

    this.DataContext = new AppPresenter();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM