2011-01-11 117 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; 
     } 
    }