Creating a dynamic checkboxes against the list of items using mvvm light wpf?
I have the following scenario:
I have one window say MainWindow where I am displaying the list of activities as per the specific user from the database. There is a one button present on the window. By clicking on that button a new window is getting opened having all the list of activities from the master table. Now I want add a chechbox on the second window against each item dynamically so that user can select/deselect the activities. Those selected/deselected values should save in the database and Parent/MainWindow should refreshed after clicking on the don开发者_如何学Pythone button and changes should reflect in the MianWindow. But I am not getting how to dynamically creating the checkboxes against each list item and binding with the xaml and select/deselect the checkbox.
Kindly suggest with samples or examples.
Thanks
You can customize your listviewitem using the ListView's ItemTemplate. Add a checkbox and a textblock to a panel which would constitute your datatemplate.
Update
The Model:
public class Activity
{
public Activity(int id, string name)
{
ID = id;
Name = name;
}
public int ID { get; set; }
public string Name { get; set; }
}
The ViewModel for ListViewItem in Second Window:
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; }
}
The 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());
}
}
}
The ViewModel for SecondWindow:
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)));
}
}
}
The XAML:
<ListView ItemsSource="{Binding AllActivities}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=Name}" />
<CheckBox IsChecked="{Binding Path=IsSelected}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListView>
精彩评论