如何使用mvvm在数据库中保存复选框选中的值?

时间:2018-01-29 05:17:02

标签: c# wpf mvvm

我有多个复选框,可根据数据库值进行选中/取消选中。 现在我想使用MVVM将检查的值(通过将未检查的值作为选中)保存到数据库中。 我试过这样的: -

的Xaml

<Window.DataContext>
    <VM:UserModuleMappingViewModel></VM:UserModuleMappingViewModel>
</Window.DataContext>

<Grid>
    <Grid.ColumnDefinitions>

    </Grid.ColumnDefinitions>

    <Label FontSize="17" Content="User Id:" Margin="30,10,187,203" RenderTransformOrigin="0.499,1.597" Grid.Row="1"/>
    <Label FontSize="15" Grid.Column="0" Content="Modules:"  RenderTransformOrigin="0.499,1.597" Grid.Row="1" Margin="30,56,187,150"/>
    <ComboBox Name="cmbuserId" Height="25" Width="120" 
              ItemsSource="{Binding ListData}" SelectedItem="{Binding SelectedItem}"
              DisplayMemberPath="UserId" VerticalAlignment="Top" Margin="123,16,49,0"/>
    <ListBox Name="list" ItemsSource="{Binding comboBoxItems}" Margin="127,65,53,92" SelectionMode="Extended" Height="300" Width="300">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <CheckBox  Name="checkModules" Content="{Binding Module_name }"  
                      Margin="3" VerticalAlignment="Center" Command="{Binding checkedCommand}"
                      IsChecked="{Binding Path=IsSelected,  Mode=TwoWay}"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    <Button Content="Save" Command="{Binding AddCommand}"  ToolTip="Save" Margin="140,0,120,26" Width="40" Height="21" VerticalAlignment="Bottom"/>
</Grid>

模型

class UserModuleMapping : INotifyPropertyChanged
{
    public string user_id { get; set; }
    public string Module_name { get; set; }
    public string Module_Id { get; set; }
    public string UserId { get; set; }

    private bool isSelected;
    public bool IsSelected
    {
        get { return isSelected; }
        set
        {
            isSelected = value;
            OnPropertyChanged("IsSelected");
        }
    }

    private ObservableCollection<UserModuleMapping> _listData;

    public ObservableCollection<UserModuleMapping> ListData
    {
        get { return _listData; }
        set { _listData = value; OnPropertyChanged("ListData"); }
    }

    public ObservableCollection<UserModuleMapping> GetListData()
    {
        ListData = new ObservableCollection<UserModuleMapping>();
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            string qry = "";
            qry = "select User_Id,EMP_Name from User_Id";
            con.Open();
            SqlCommand cmd = new SqlCommand();
            SqlDataAdapter sa = new SqlDataAdapter(qry, con);
            DataTable dt = new DataTable();
            sa.Fill(dt);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                UserModuleMapping ck = new UserModuleMapping();
                ck.UserId = dt.Rows[i]["User_Id"].ToString();
                ListData.Add(ck);
            }

            return ListData;
        }
    }

    //---------------------------for checkbox generation---------------------------------

    private ObservableCollection<UserModuleMapping> _modulesData;

    public ObservableCollection<UserModuleMapping> ModulesData
    {
        get { return _modulesData; }
        set { _modulesData = value; OnPropertyChanged("ModulesData"); }
    }
    public ObservableCollection<UserModuleMapping> getModules()
    {
        ModulesData = new ObservableCollection<UserModuleMapping>();
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            string qry = "";
            qry = "select * from [dbo].[Module_Mstr]";
            con.Open();
            SqlCommand cmd = new SqlCommand();
            SqlDataAdapter sa = new SqlDataAdapter(qry, con);
            DataTable dt = new DataTable();
            sa.Fill(dt);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                UserModuleMapping cl = new UserModuleMapping();
                cl.Module_name = dt.Rows[i]["Module_Name"].ToString();
                cl.IsSelected = true;
                ModulesData.Add(cl);
                //IEnumerable<String> selectedData = ModulesData.Where(d => d.IsSelected).Select(d => d.Module_name);

            }
            return ModulesData;
        }
    }

    //--------------------end------------------------------------------------------------

    //---------------------------for combobox change based checkbox-----------------------

    private ObservableCollection<UserModuleMapping> _userModule;

    public ObservableCollection<UserModuleMapping> UserModule
    {
        get { return _userModule; }
        set { _userModule = value; OnPropertyChanged("UserModule"); }
    }
    public ObservableCollection<UserModuleMapping> getuserModules(string user_id)
    {
        UserModule = new ObservableCollection<UserModuleMapping>();
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            string qry = "";
            qry = "  select umap.User_Id,umap.Module_Id,mod_mstr.Module_Name  from Module_Mstr mod_mstr left" +
            " join [dbo].[UserModule_Map] umap  on mod_mstr.Module_Id = umap.Module_Id and umap.User_Id = '" + user_id + "'";
            con.Open();
            SqlCommand cmd = new SqlCommand();
            SqlDataAdapter sa = new SqlDataAdapter(qry, con);
            DataTable dt = new DataTable();
            sa.Fill(dt);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                UserModuleMapping cli = new UserModuleMapping();
                cli.Module_name = dt.Rows[i]["Module_Name"].ToString();
                cli.Module_Id = dt.Rows[i]["Module_Id"].ToString();
                if (cli.Module_Id == "" || cli.Module_Id == null)
                {
                    cli.IsSelected = false;
                }
                else
                {
                    cli.IsSelected = true;
                }
                UserModule.Add(cli);
                //IEnumerable<String> selectedData = UserModule.Where(d => d.IsSelected).Select(d => d.Module_name);

            }
            return UserModule;

        }
    }

    //--------------------end------------------------------------------------------------

    //private ObservableCollection<UserModuleMapping> data;
    //public ObservableCollection<UserModuleMapping> Data
    //{
    //    get { return data; }
    //    set { data = value; OnPropertyChanged("Data"); }
    //}


    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

视图模型

class UserModuleMappingViewModel : ModelBase
{
    public string userid { get; set; }
    public ObservableCollection<UserModuleMapping> comboBoxItems { get; set; }
    public ObservableCollection<UserModuleMapping> checkboxItems { get; set; }
    public ObservableCollection<UserModuleMapping> checkboxCommand { get; set; }
    public ICommand GetData { get; set; }
    public ICommand GetMod { get; set; }

    public UserModuleMapping _selectedItem;
    public UserModuleMapping SelectedItem
    {
        get { return _selectedItem; }
        set
        {
            _selectedItem = value;
            GetUserModules();
            OnPropertyChanged("comboBoxItems");
        }
    }

    private ObservableCollection<UserModuleMapping> _listData;
    public ObservableCollection<UserModuleMapping> ListData
    {
        get { return _listData; }
        set { _listData = value; OnPropertyChanged("ListData"); }

    }

    private ObservableCollection<UserModuleMapping> _modulesData;
    public ObservableCollection<UserModuleMapping> ModulesData
    {
        get { return _modulesData; }
        set { _modulesData = value; OnPropertyChanged("UserModuleMappi"); }
    }

    private ObservableCollection<UserModuleMapping> _userModules;
    public ObservableCollection<UserModuleMapping> UserModules
    {
        get { return _userModules; }
        set { _userModules = value; OnPropertyChanged("UserModules"); }
    }


    public UserModuleMappingViewModel()
    {
        GetListData();
        GetModulesData();

    }

    public void GetListData()
    {
        ListData = new ObservableCollection<UserModuleMapping>();
        UserModuleMapping model = new UserModuleMapping();
        ListData = model.GetListData();
    }

    public void GetModulesData()
    {
        ModulesData = new ObservableCollection<UserModuleMapping>();
        UserModuleMapping model = new UserModuleMapping();
        comboBoxItems = new ObservableCollection<UserModuleMapping>(model.getModules());

    }

    public void GetUserModules()
    {
        UserModules = new ObservableCollection<UserModuleMapping>();
        UserModuleMapping model = new UserModuleMapping();
        comboBoxItems = new ObservableCollection<UserModuleMapping>(model.getuserModules(_selectedItem.UserId));

    }

    private RelayCommand addCommand;
    public ICommand AddCommand
    {
        get { return addCommand ?? (addCommand = new RelayCommand(() => saveuserModules())); }
    }

    //-------------------------save checkbox values------------------------------

    private ObservableCollection<UserModuleMapping> _saveUserMappingModules;
    public ObservableCollection<UserModuleMapping> SaveUserModule
    {
        get { return _saveUserMappingModules; }
        set { _saveUserMappingModules = value; OnPropertyChanged("UserModule"); }
    }

    public ObservableCollection<UserModuleMapping> saveuserModules()
    {
        UserModuleMapping model = new UserModuleMapping();
        SaveUserModule = new ObservableCollection<UserModuleMapping>();

        if (SelectedItem.UserId != null || SelectedItem.UserId != "")
        {
            SaveUserModule = new ObservableCollection<UserModuleMapping>(model.getuserModules(_selectedItem.UserId));
            //if (model.IsSelected == false)
            //{
            checkboxCommand = new ObservableCollection<UserModuleMapping>(model.getuserModules(_selectedItem.UserId));
            IEnumerable<String> selectedData = SaveUserModule.Where(d => d.IsSelected).Select(d => d.Module_name);
            foreach (var items in SaveUserModule)
            {
                UserModuleMapping mapp = new UserModuleMapping();
                mapp.user_id = items.user_id;
                mapp.Module_name = items.Module_name;
                SaveUserModule.Add(mapp);
            }
        }
        else
        {
        }
        return SaveUserModule;
    }
}

“selectedData”应具有已选中和未选中的值。我将如何实现这一目标?

0 个答案:

没有答案