应使用WPF-MVVM根据数据库值检查/取消选中复选框

时间:2018-01-18 09:09:05

标签: wpf checkbox mvvm binding

我正在使用WPF-MVVM,我有一个用户控制窗口,其中包含一个组合框和复选框。    Combo值和Checkbox内容是动态的。    我有问题是根据组合框更改检查/取消检查值。  如果它是WPF窗口但在用户控制窗口上没有正常工作。

<UserControl x:Class="MVVM_Ribbon.Views.UserModuleMappi"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:MVVM_Ribbon.Views"
         mc:Ignorable="d" 
         xmlns:VM="clr-namespace:MVVM_Ribbon.ViewModel"
         xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
         d:DesignHeight="300" d:DesignWidth="300">
<!--<UserControl.DataContext>
    <VM:UserModuleMappingViewModel>
         </VM:UserModuleMappingViewModel>
</UserControl.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 comboBoxItems}" 
              VerticalAlignment="Top" Margin="123,16,49,0"/>

    <ListBox Name="list" ItemsSource="{Binding checkboxItems }" Margin="127,65,53,92" SelectionMode="Extended">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <CheckBox  Name="checkModules" Content="{Binding}" Margin="3" VerticalAlignment="Center"
                               Command="{Binding CheckCommand, Mode=TwoWay}"
                               IsChecked="{Binding Path=IsChecked, Mode=TwoWay}"  />

                    <ContentPresenter Content="{Binding}" Margin="1"/>

                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

    </Grid>

   Model.cs

    namespace MVVM_Ribbon.Model
   {
      class UserModuleMapping : INotifyPropertyChanged
     {
    private ObservableCollection<string> _listData;

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


    public ObservableCollection<string> GetListData()
    {
        ListData = new ObservableCollection<string>();
        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++)
            {
                string UserId = dt.Rows[i]["User_Id"].ToString();
                ListData.Add(UserId);
            }


            return ListData;
        }
    }

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

    private ObservableCollection<string> _modulesData;

    public ObservableCollection<string> ModulesData
    {
        get { return _modulesData; }
        set { _modulesData = value; OnPropertyChanged("ModulesData"); }
    }
    public ObservableCollection<string> getModules()
    {
        ModulesData = new ObservableCollection<string>();
        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++)
            {
                string mod_name = dt.Rows[i]["Module_Name"].ToString();
                ModulesData.Add(mod_name);
            }
            return ModulesData;
        }
    }


    private ObservableCollection<string> _userModule;

    public ObservableCollection<string> UserModule
    {
        get { return _userModule; }
        set { _userModule = value; OnPropertyChanged("UserModule"); }
    }
    public ObservableCollection<string> getuserModules(string user_id)
    {
        UserModule = new ObservableCollection<string>();
        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[dbo].[UserModule_Map] umap,Module_Mstr mod_mstr where" +
                  " umap.Module_Id = mod_mstr.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++)
            {
                string user_mod_name = dt.Rows[i]["Module_Name"].ToString();
                UserModule.Add(user_mod_name);
            }
            return UserModule;

        }
    }
    public event PropertyChangedEventHandler PropertyChanged;

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

}}

ViewModel.cs

     class UserModuleMappingViewModel : ModelBase
{
    string user_Id;

    public CollectionView comboBoxItems { get; set; }
    public CollectionView checkboxItems { get; set; }
    public bool Loaded { get; set; }
    public ICommand GetData { get; set; }
    public ICommand GetMod { get; set; }


    private bool isChecked;
    private ICommand checkCommand;

    public bool IsChecked
    {
        get { return isChecked; }
        set
        {
            isChecked = value;
            OnPropertyChanged("IsChecked");
        }
    }

    public ICommand OnCheckedCommand
    {
        get
        {

            return checkCommand;
        }
        set
        {
            checkCommand = value;
            OnPropertyChanged("OnCheckedCommand");
        }
    }

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

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

    private ObservableCollection<string> _userModules;
    public ObservableCollection<string> UserModules
    {
        get { return _userModules; }
        set { _userModules = value; OnPropertyChanged("UserModules"); }
    }
    public UserModuleMappingViewModel()
    {
        GetListData();
        GetModulesData();
        //GetUserModules();
        GetData = new RelayCommand(GetItemsData);
        GetMod = new RelayCommand(GetModules);
        IsChecked = true;
    }
    private void GetItemsData(object obj)
    {
        var Item = comboBoxItems.CurrentItem;
        MessageBox.Show(Item.ToString());
    }
    private void GetModules(object obj)
    {
        var modul = checkboxItems.CurrentItem;
        MessageBox.Show(modul.ToString());
    }
    private void GetListData()
    {
        ListData = new ObservableCollection<string>();
        UserModuleMapping model = new UserModuleMapping();
        ListData = model.GetListData();
        comboBoxItems = new CollectionView(model.GetListData());
        comboBoxItems.MoveCurrentTo(ListData[0]);
        comboBoxItems.CurrentChanged += ComboBoxItems_CurrentChanged;
    }
    private void GetModulesData()
    {
        ModulesData = new ObservableCollection<string>();
        UserModuleMapping model = new UserModuleMapping();
        ModulesData = model.getModules();
        checkboxItems = new CollectionView(model.getModules());
        checkboxItems.MoveCurrentTo(ModulesData[0]);
    }

    private void GetUserModules()
    {
        UserModules = new ObservableCollection<string>();
        UserModuleMapping model = new UserModuleMapping();
        UserModules = model.getuserModules(user_Id);
        //checkboxItems = new CollectionView(model.getuserModules(user_Id));
        //checkboxItems.MoveCurrentTo(UserModules[0]);
    }

    private void ComboBoxItems_CurrentChanged(object sender, EventArgs e)
    {
        if (Loaded)
        {
            user_Id = ((CollectionView)sender).CurrentItem.ToString();
            GetUserModules();

        }
        Loaded = true;
    }
    public void ShowMessage(object obj)
    {
        MessageBox.Show(obj.ToString());
    }



}

1 个答案:

答案 0 :(得分:0)

您的CheckBox命令设置错误,因为您绑定了CheckCommand,但ViewModel中有OnCheckedCommand。此外,如果要使用命令,可以删除IsChecked属性并执行以下操作

<CheckBox  Name="checkModules" Content="{Binding}" Margin="3" VerticalAlignment="Center"
                            Command="{Binding DataContext.CheckCommand,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListBox}",
                           CommandParameter="{Binding IsChecked, RelativeSource={RelativeSource Self}, Mode=OneWay}" />