使用mvvm light wpf针对项目列表创建动态复选框?

时间:2010-07-02 08:56:54

标签: wpf mvvm mvvm-light

我有以下情况:

我有一个窗口说MainWindow,我根据数据库中的特定用户显示活动列表。窗口上有一个按钮。通过单击该按钮,将打开一个新窗口,其中包含主表中的所有活动列表。现在我想在第二个窗口上针对每个项目动态添加一个chechbox,以便用户可以选择/取消选择活动。这些选定/取消选择的值应保存在数据库中,并且在单击完成按钮后应刷新Parent / MainWindow,并且更改应反映在MianWindow中。但我没有得到如何针对每个列表项动态创建复选框并使用xaml绑定并选择/取消选中复选框。

请提示样品或样品。

由于

1 个答案:

答案 0 :(得分:3)

您可以使用ListView的ItemTemplate自定义listviewitem。添加一个复选框 以及构成您的数据模板的面板的文本块。

<强>更新

型号:

public class Activity
{         
    public Activity(int id, string name) 
    { 
        ID = id;
        Name = name;        
    } 

    public int ID { get; set; }
    public string Name { get; set; }    

}

第二个窗口中ListViewItem的ViewModel:

public class ActivityViewModel
{
    Activity _model;

    public ActivityViewModel(Activity model, bool isSelected) 
    { 
        _model = model;
        IsSelected = isSelected; 
    }        

    public string Name { get { return _model.Name; } }

    /* Since the view has a checkbox and it requires a bool value for binding
       we create this property */
    public Nullable<bool> IsSelected { get; set; }       
}

DataAccess

public class DaoDailyActivities 
{ 
    string activityName = "";  
    bool IsSelected; 

    SqlConnection con = new SqlConnection("server=172.16.32.68;database=ParentalHealth;uid=sa;pwd=Emids123"); 

    public IEnumerable<Activity> GetActivities() 
    {  
        SqlCommand cmd = new SqlCommand("SP_GetActivities", con); 
        cmd.CommandType = CommandType.StoredProcedure;
        con.Open(); /* It is safe to open connections in a try block */

        SqlDataReader readerActivities = cmd.ExecuteReader();
        while (readerActivities.Read()) 
        {           
            yield new Activity(readerActivities["ActivityID"].ToString(), readerActivities["ActivityName"].ToString());            
        } 
    }         
} 

SecondWindow的ViewModel:

public class SecondWindowViewModel : ViewModelBase 
{
    DaoDailyActivities _rep = new DaoDailyActivities();

    public ObservableCollection<ActivityViewModel> AllActivities { get; set; }

    public SecondWindowViewModel()
    {
        LoadAllActivities();
    } 

    LoadAllActivities()
    {
        foreach(Activity activity in _rep.GetActivities())
        {
            AllActivities.Add(new ActivityViewModel(activity, (activity.ID % 2 == 0)));
        }
    }
}

XAML:

<ListView ItemsSource="{Binding AllActivities}">
    <ListBox.ItemTemplate>
     <DataTemplate>
       <StackPanel>
         <TextBlock Text="{Binding Path=Name}" />
         <CheckBox IsChecked="{Binding Path=IsSelected}" />
       </StackPanel>
     </DataTemplate>
   </ListBox.ItemTemplate> 
</ListView>