I'm trying to make a screen with lots of controls using mvvm It's a settings screen that I want to allow the user to search for the settings he wants, leaving the others invisible.
I wouldn't want to have to create a property for every control, instead I'd like to create a list and index every item from it to a control.
However, for ease of maintenance, I would like to use a custom indexer, in this case a string
I created this list
public class ObservConfigList: ObservableCollection<ConfigModel>
{
public ConfigModel this[string find]
{
get => this.FirstOrDefault(x => x.Config == find);
set
{
var indice = this.IndexOf(this.FirstOrDefault(x => x.Config == find));
if (indice >= this.Count)
this[indice] = value;
}
}
}
And the xaml was like this
<Grid DataContext="{Binding ListConfig[EMPRESA]}" Style="{StaticResource visibConvert}">
<Grid.ColumnDefinitions>
<ColumnDefinition Style="{StaticResource col1}"/>
<ColumnDefinition Style="{StaticResource col2}"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Descricao}"/>
<ComboBox Grid.Column="1" Text="{Binding Valor}">
<ComboBoxItem Content="SIM"/>
<ComboBoxItem Content="NÃO"/>
</ComboBox>
</Grid>
my viewmodel
private ObservConfigList _listConfig = new ObservConfigList();
public ObservConfigList ListConfig { get => _listConfig; set => _listConfig = value; }
private void ConfigViewModel()
{
ConfigEmpresa = new ConfigModel();
ConfigEmpresa.Descricao = "Empresa";
ConfigEmpresa.IsVisible = true;
ConfigEmpresa.Config = "EMPRESA";
ListConfig.Add(ConfigEmpresa);
}
It even worked as I expected at runtime, but I don't know if this is the correct way to do it and in xaml a notification keeps showing that the EMPRESA index is invalid.
CodePudding user response:
I found this question
and modified the code from my list to do so
public class ObservConfigList
{
private ObservableCollection<ConfigModel> _listConfig = new ObservableCollection<ConfigModel>();
public ObservableCollection<ConfigModel> ListConfig { get => _listConfig; set => _listConfig = value; }
public ConfigModel this[string find]
{
get => ListConfig.FirstOrDefault(x => x.Config == find);
set
{
var indice = ListConfig.IndexOf(ListConfig.FirstOrDefault(x => x.Config == find));
if (indice >= ListConfig.Count)
ListConfig[indice] = value;
}
}
}
This way it no longer displays error notifications.