c# - WPF数据绑定(bind)问题

标签 c# wpf .net-4.0 binding

我是 WPF 新手,在尝试使用自定义对象列表填充 ListView 时遇到了一些困难。

internal class ApplicationCode
{
    public int Code { get; set; }

    public IEnumerable<string> InstrumentCodes { get; set; }
}

我有一个 ApplicationCode 列表,我将其设置为 ItemsSource 到 ListView。我需要将 ApplicationCode.Code 显示为字符串,并为其余列显示一个复选框,可以根据列名是否包含在 InstrumentCodes 集合中选中/取消选中该复选框。

为了设置复选框,我在数据绑定(bind)上使用了一个转换器:

<DataTemplate x:Key="InstrumentCodeTemplate">
  <CheckBox IsEnabled="False" IsChecked="{Binding Mode=OneTime, Converter={StaticResource InstrumentSelectionConverter}}" />
</DataTemplate>

我遇到的问题是因为在单元格数据绑定(bind)时我无法知道哪个是当前列并且我无法设置 ConverterParameter。

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
  ApplicationCode appCode = value as ApplicationCode;

  return appCode != null && appCode.InstrumentCodes.Contains(parameter.ToString());
}

小例子:

    Id  | Code1 | Code3 | Code4
--------------------------------
    123 |  True | False | True

第 1 行的数据:ApplicationCode.InstrumentCodes {Code1, Code4}

有没有办法找出列索引或名称?或者有另一种方法来解决这个问题?

最佳答案

列名应该只是一个视觉效果;这意味着所需的数据都应该驻留在底层对象模型中。因此每一行数据都是一个对象。

也许对您的代码进行重组就足够了,这也将消除对转换器的需求...请记住,这是一个用来理解想法的示例,需要针对实际使用进行修改。

    internal class ApplicationCode
    {
        private CodeService _codeService = new CodeService();

        public int Code { get; set; }
        public bool IsValidCode
        {
            get
            {
                return _codeService.DoesIntrumentCodeExist(Code.ToString());
            }
        }
    }

    internal class CodeService
    {
        private IEnumerable<string> _instrumentCodes;

        public CodeService()
        {
            //instantiate this in another way perhaps via DI....
            _instrumentCodes = new List<string>();
        }

        public bool DoesIntrumentCodeExist(String instrumentCode)
        {
            foreach (String code in _instrumentCodes)
            {
                if (code == instrumentCode)
                    return true;
            }

            return false;
        }
    }

关于c# - WPF数据绑定(bind)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4659276/

相关文章:

C# XML 解析 - 搜索特定元素

c# - 奇怪的颜色代码?转换为十六进制?

c# - 从 c# 打开 .exe(c 程序)

c# - ASP.NET Core 中的 PostAsJsonAsync 方法在哪里?

c# - 在 WPF 中动态更改 Setter 值

c# - 如何获取 DataGrid 中刚刚编辑的单元格的行索引和单元格索引

winforms - 如何在 WinForm 线程上获取 WinForm 同步上下文或调度

c# - ASP.NET Core 2.0 docker 容器在 Linux 上崩溃,退出代码为 132 (SIGILL)

wpf - Binding UpdateSourceTrigger=Explicit,在程序启动时更新源

c# - 如何将数组拆分为一组 n 个元素?