0

I've read through probably 20 different posts and still can put together what I'm looking to do (maybe I'm going about it the wrong way?).

I want to make a window with a few checkboxes. These checkboxes need to have their IsChecked value bound to a member variable of an object in a List.

I'm trying something like this:

XAML

<CheckBox IsChecked="{Binding Features[0].Selected, Mode=TwoWay}">
    <TextBlock Text="Feature 1" />
</CheckBox>
<CheckBox IsChecked="{Binding Features[1].Selected, Mode=TwoWay}">
    <TextBlock Text="Feature 2" />
</CheckBox>

ViewModel

  public static enum MyFeatureEnum
  {
     FEATURE1,
     FEATURE2,
     FEATURE3,
     ...
  }

  public class Feature : INotifyPropertyChanged
  {
     private bool _supported;
     private bool _visible;
     private bool _selected;
     public MyFeatureEnum FeatureEnum { get; set; }

     public bool Supported
     {
        get { return _supported; }
        set { _supported = value; NotifyPropertyChanged("Supported"); }
     }
     public bool Visible
     {
        get { return _visible; }
        set { _visible = value; NotifyPropertyChanged("Visible"); }
     }
     public bool Selected
     {
        get { return _selected; }
        set { _selected = value; NotifyPropertyChanged("Selected"); }
     }

     public Feature(MyFeatureEnum featureEnum)
     {
        _supported = false;
        _visible = false;
        _selected = false;
        FeatureEnum = featureEnum;
     }

     public event PropertyChangedEventHandler PropertyChanged;
     private void NotifyPropertyChanged(string propertyName)
     {
        if (PropertyChanged != null)
        {
           PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
     }
  }

  public List<Feature> Features { get; set; }

  public InstallViewModel()
  {
     ...
     // Generate the list of features
     Features = new List<Feature>();
     foreach (MyFeatureEnum f in Enum.GetValues(typeof(MyFeatureEnum)))
     {
        Features.Add(new Feature(f));
     }
     ...
  }

This works.

What I want is to replace:

<CheckBox IsChecked="{Binding Features[0].Selected, Mode=TwoWay}">

with something like:

<CheckBox IsChecked="{Binding Features[InstallViewModel.MyFeatureEnum.FEATURE1].Selected, Mode=TwoWay}">

Is this possible?

jbudreau
  • 1,287
  • 1
  • 10
  • 22

1 Answers1

1

Is this possible?

Not using a List<Feature> but you could use a Dictionary<MyFeatureEnum, Feature>:

public class InstallViewModel
{
    public Dictionary<MyFeatureEnum, Feature> Features { get; set; }

    public InstallViewModel()
    {
        // Generate the list of features
        Features = new Dictionary<MyFeatureEnum, Feature>();
        foreach (MyFeatureEnum f in Enum.GetValues(typeof(MyFeatureEnum)))
        {
            Features.Add(f, new Feature(f));
        }
    }
}

<CheckBox IsChecked="{Binding Features[FEATURE1].Selected, Mode=TwoWay}" />
mm8
  • 163,881
  • 10
  • 57
  • 88