我是 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/