I am relatively new to the whole concept of WPF and MVVM, and I am looking for best practice tips. I have a solution that works, but it looks like I can skip some great XAML syntax that will simplify all this.
I have a string field in a database table that is stored as a CSV, for example. "COTOPES". Perhaps I should have done this as a many-to-many relationship in my entity data model, but this is a great discussion on best practice.
In my XAML, I use multibinding in a ListBox that contains CheckBoxes. The scope of options is determined at runtime, and the ListBox generates CheckBoxes using the DataTemplate. Here's the XAML:
<ListBox Grid.Column="3" Grid.Row="8" Grid.RowSpan="2" Name="brandedProductsListBox" Margin="3" ItemsSource="{Binding Source={StaticResource brandedProductLookup}}" IsSynchronizedWithCurrentItem="True" TabIndex="475">
<ItemsControl.ItemTemplate>
<DataTemplate>
<CheckBox Margin="3" Content="{Binding Path=BrandedProductName}" Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked">
<CheckBox.IsChecked>
<MultiBinding Converter="{StaticResource brandedProductToBoolean}">
<Binding Source="{StaticResource projectsView}" Path="BrandedProducts" />
<Binding Path="BrandedProductName" />
</MultiBinding>
</CheckBox.IsChecked>
</CheckBox>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ListBox>
CheckBoxes. ConvertBack- CSV, , , BrandedProductName, , , . :
public class BrandedProductToBooleanConverter : IMultiValueConverter
{
public object Convert(object[] value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null) {
return false;
}
else {
string brandedProducts = value[0] as string;
string brandedProduct = value[1] as string;
return brandedProducts == null ? false : brandedProducts.Contains(brandedProduct);
}
}
public object[] ConvertBack(object value, Type[] targetType, object parameter, CultureInfo culture)
{
return null;
}
}
So Convert CheckBoxes, , , , Checked UnChecked CheckBox , :
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
if (projectView.IsAddingNew) {
CheckBox checkBox = sender as CheckBox;
NewProject project = projectView.CurrentAddItem as NewProject;
if (project.BrandedProducts == null) {
project.BrandedProducts = (string)checkBox.Content;
}
else {
project.BrandedProducts += ", " + (string)checkBox.Content;
}
}
e.Handled = true;
}
private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
{
if (projectView.IsAddingNew) {
CheckBox checkBox = sender as CheckBox;
NewProject project = projectView.CurrentAddItem as NewProject;
if (project.BrandedProducts != null) {
project.BrandedProducts = project.BrandedProducts.Replace((string)checkBox.Content + ", ", "").Replace(", " + (string)checkBox.Content, "");
}
}
e.Handled = true;
}
, , ? , , / . - MVVM ViewModel ?
,
Ray