2017-08-07 25 views
0

對象我已經通過大概20個不同崗位閱讀並仍然可以放在一起就是我希望做的(也許我會約了錯誤的方式?)。XAML:綁定到器isChecked列出使用枚舉指數

我想打一個窗口,有一些複選框。這些複選框需要將它們的IsChecked值綁定到List中對象的成員變量。

我想是這樣的:

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> 

視圖模型

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)); 
    } 
    ... 
    } 

這工作。

我要的是替換:

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

的東西,如:

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

這可能嗎?

回答

1

這可能嗎?

不使用List<Feature>但你可以使用一個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}" /> 
+0

哈利路亞!這真的很簡單:D – jbudreau