2011-01-11 119 views
2

我是WPF的新手,当我尝试使用自定义对象列表填充ListView时遇到了一些困难。WPF数据绑定问题

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

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

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

为了设置我使用转换器上的数据绑定的复选框:

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

我的问题是,因为我不知道这是在细胞数据的时间目前列绑定和我无法设置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 {编码1,码4}

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

+1

什么是你的XAML代码的绑定的ListView? – 2011-01-11 15:36:58

+0

嗨马丁。绑定在后面的代码中进行:AcnList.ItemsSource = repository.GetApplicationCodes(); GetApplicationCodes返回一个列表 Costin 2011-01-11 16:18:29

回答

0

我到目前为止所得到的解决方案是动态添加列并在每列上设置ConverterParameter。

foreach (var instrument in instruments) 
{ 
    var column = new GridViewColumn 
         { 
          HeaderTemplate = GetColumnHeaderTemplate(instrument), 
          CellTemplate = GetColumnCellTemplate(instrument), 
          Header = instrument, 
         }; 

    view.Columns.Add(column); 
} 

private static DataTemplate GetColumnCellTemplate(string instrument) 
{ 
    var binding = new Binding 
    { 
     ConverterParameter = instrument, 
     Converter = new InstrumentSelectionConverter(), 
     Mode = BindingMode.OneWay 
    }; 

    var template = new DataTemplate(); 
    template.VisualTree = new FrameworkElementFactory(typeof(CheckBox)); 
    template.VisualTree.SetBinding(ToggleButton.IsCheckedProperty, binding); 

    return template; 
} 

我知道这是不是最好的解决方案,我会很感激,如果有人能告诉我一个办法直接从的.xaml做到这一点。

1

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

也许你的代码重组就足够了,这也将消除转换器的需要...请记住这是一个想法,并需要修改实际使用的例子。

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