I have a ListBox
in WPF and it has CheckBox
items inside. I'm splitting the checked checkboxes with the following code in XAML codebehind.
StringBuilder sbMonths = new StringBuilder();
StringBuilder sbMonthNames = new StringBuilder();
string months;
string monthNames;
foreach (var item in ListBox.Items)
{
if (item is CheckBox)
{
var chk = item as CheckBox;
if ((bool)chk.IsChecked)
{
sbMonths.Append(chk.Tag);
sbMonths.Append(',');
sbMonthNames.Append(chk.Content.ToString());
sbMonthNames.Append('-');
}
}
}
months = sbMonths.ToString();
monthNames = sbMonthNames.ToString();
int lastIndexOfMonths = months.LastIndexOf(',');
int lastIndexOfMonthNames = monthNames.LastIndexOf('-');
if (lastIndexOfMonths > -1)
{
months = months.Remove(lastIndexOfMonths);
monthNames = monthNames.Remove(lastIndexOfMonthNames);
.... I do more here
}
The thing is that I have no idea how to do this using MVVM. Would you provide some solutions?
XAML:
<ListBox Name="ListBox" HorizontalAlignment="Left" Height="149" Margin="23,47,0,0" VerticalAlignment="Top" Width="210">
<ComboBoxItem Content="-- Ay Seçiniz --"/>
<CheckBox Content="Ocak" Tag="1"/>
<CheckBox Content="Şubat" Tag="2"/>
<CheckBox Content="Mart" Tag="3"/>
<CheckBox Content="Nisan" Tag="4"/>
<CheckBox Content="Mayıs" Tag="5"/>
<CheckBox Content="Haziran" Tag="6"/>
<CheckBox Content="Temmuz" Tag="7"/>
<CheckBox Content="Ağustos" Tag="8"/>
<CheckBox Content="Eylül" Tag="9"/>
<CheckBox Content="Ekim" Tag="10"/>
<CheckBox Content="Kasım" Tag="11"/>
<CheckBox Content="Aralık" Tag="12"/>
</ListBox>
Here's how you would do this using MVVM.
First, create a Model (MVVM) for your months.
Now, you want to expose those in your ViewModel (MVVM) both as a collection of all months.
And then bind to them in your View (MVVM)
That's how MVVM works.
Use Following Code:
XAML:
Code:
Using above code at any point of time in
ViewModel
, you will be able to get the selected items from collectionMonths
and you can apply your code as you want.