【问题标题】:WPF Binding custom list indexerWPF Binding 自定义列表索引器
【发布时间】:2021-12-18 19:35:24
【问题描述】:

我正在尝试使用 mvvm 制作一个带有很多控件的屏幕 这是一个设置屏幕,我想让用户搜索他想要的设置,而让其他人不可见。

我不想为每个控件创建一个属性,而是想创建一个列表并将其中的每个项目索引到一个控件。

但是,为了便于维护,我想使用自定义索引器,在本例中为字符串

我创建了这个列表

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

xaml 是这样的

<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>

我的视图模型

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

它甚至在运行时按我预期的那样工作,但我不知道这是否是正确的方法,并且在 xaml 中,通知不断显示 EMPRESA 索引无效。

【问题讨论】:

  • 如果它在运行时按预期工作并且设计器没有崩溃,那么你做得很好。 xaml 编辑器并不完美。它可能检测到在 ObservableCollection 类中实现的整数索引并抱怨字符串
  • 你可能是对的,但是看到这个错误出现在 vs. 甚至编译和工作的错误列表中真的很烦人,错误列表将填满这些通知,因为我会这样做每个控件。

标签: c# wpf


【解决方案1】:

我找到this question

并修改了我列表中的代码

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

这样它就不再显示错误通知了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-01
    • 1970-01-01
    • 2013-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多