2012-06-15 2 views
4

Я ищу сетку WinForms или WPF, которая может отображать различные элементы управления (текстовые поля и выпадающие списки на данный момент) в том же столбце. Он также должен иметь функции treelist/treeview, чтобы отображалась иерархия между строками (узлами). Мне нужно иметь возможность добавлять элемент управления во время выполнения в ячейку и программно изменять высоты и ширину столбцов.
Я искал какое-то время, но пока не повезло. Какие-либо предложения? Помощь очень ценится.Несвязанная сетка с различными типами элементов управления в одном столбце

ответ

0

Если оплата за такой компонент является вариантом, я бы очень рекомендовал компоненты Telerik. У них много контроля, и техническая поддержка велик.

Вы можете посмотреть на некоторые примеры, чтобы узнать, если их продукция соответствии с вашими потребностями:

Telerik GridView for WPF

Telerik TreeListView for WPF

+0

Спасибо Matthias за быстрый ответ, это вариант, и я буду проверять его :) –

3

Результаты этого ответа.

enter image description here

Я хотел бы использовать стандартный WPF DataGrid, нет необходимости платить деньги только все же, вы можете выбрать столбец шаблона и просто связывание немного данных внутри него, на примере ниже, имеет очень простой класс, который я привязываю к сетке.

public class ListItemType 
{ 
    public int Type { get; set; } 
    public string Text { get; set; } 
} 

Этот класс, очевидно, может быть что угодно, но в этом примере я типа к 1 или 2 установки, любой объект в связанном списке, который имеет тип 1 дан кнопку, чтобы представить его и что-нибудь с a Type = 2 предоставляется CheckBox для его представления.

XAML для datagrid выглядит следующим образом. (Отступы ++)

<DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False" Height="200" HorizontalAlignment="Left" Margin="10,10,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="200" > 
    <DataGrid.Columns> 

     <!-- The template coloumn --> 
     <DataGridTemplateColumn> 
      <DataGridTemplateColumn.CellTemplate> 
       <DataTemplate> 

        <!-- Each cell is put in to a content presenter so I can change it's content --> 
        <ContentPresenter> 
         <ContentPresenter.Content> 
          <Binding Path="Type"> 
           <Binding.Converter> 
            <local:SwitchConverter> 

             <local:SwitchConverterCase When="1"> 
              <Button Content="{Binding Text}"></Button> 
             </local:SwitchConverterCase> 

             <local:SwitchConverterCase When="2"> 
              <CheckBox Content="{Binding Text}" /> 
             </local:SwitchConverterCase> 


            </local:SwitchConverter> 
           </Binding.Converter> 
          </Binding> 
         </ContentPresenter.Content> 
        </ContentPresenter> 
       </DataTemplate> 
      </DataGridTemplateColumn.CellTemplate> 
     </DataGridTemplateColumn> 
    </DataGrid.Columns> 
</DataGrid> 

Переключатель преобразователя используется выше только общий конвертер, который упрощает код XAML немного, вы можете использовать любой конвертер вы хотите, но вот код который я использовал в любом случае.

/// <summary> 
/// A converter that accepts <see cref="SwitchConverterCase"/>s and converts them to the 
/// Then property of the case. 
/// </summary> 
[ContentProperty("Cases")] 
public class SwitchConverter : IValueConverter 
{ 
    // Converter instances. 
    List<SwitchConverterCase> _cases; 

    #region Public Properties. 
    /// <summary> 
    /// Gets or sets an array of <see cref="SwitchConverterCase"/>s that this converter can use to produde values from. 
    /// </summary> 
    public List<SwitchConverterCase> Cases { get { return _cases; } set { _cases = value; } } 
    #endregion 
    #region Construction. 
    /// <summary> 
    /// Initializes a new instance of the <see cref="SwitchConverter"/> class. 
    /// </summary> 
    public SwitchConverter() 
    { 
     // Create the cases array. 
     _cases = new List<SwitchConverterCase>(); 
    } 
    #endregion 

    /// <summary> 
    /// Converts a value. 
    /// </summary> 
    /// <param name="value">The value produced by the binding source.</param> 
    /// <param name="targetType">The type of the binding target property.</param> 
    /// <param name="parameter">The converter parameter to use.</param> 
    /// <param name="culture">The culture to use in the converter.</param> 
    /// <returns> 
    /// A converted value. If the method returns null, the valid null value is used. 
    /// </returns> 
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     // This will be the results of the operation. 
     object results = null; 

     // I'm only willing to convert SwitchConverterCases in this converter and no nulls! 
     if (value == null) throw new ArgumentNullException("value"); 

     // I need to find out if the case that matches this value actually exists in this converters cases collection. 
     if (_cases != null && _cases.Count > 0) 
      for (int i = 0; i < _cases.Count; i++) 
      { 
       // Get a reference to this case. 
       SwitchConverterCase targetCase = _cases[i]; 

       // Check to see if the value is the cases When parameter. 
       if (value == targetCase || value.ToString().ToUpper() == targetCase.When.ToString().ToUpper()) 
       { 
        // We've got what we want, the results can now be set to the Then property 
        // of the case we're on. 
        results = targetCase.Then; 

        // All done, get out of the loop. 
        break; 
       } 
      } 

     // return the results. 
     return results; 
    } 

    /// <summary> 
    /// Converts a value. 
    /// </summary> 
    /// <param name="value">The value that is produced by the binding target.</param> 
    /// <param name="targetType">The type to convert to.</param> 
    /// <param name="parameter">The converter parameter to use.</param> 
    /// <param name="culture">The culture to use in the converter.</param> 
    /// <returns> 
    /// A converted value. If the method returns null, the valid null value is used. 
    /// </returns> 
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 

/// <summary> 
/// Represents a case for a switch converter. 
/// </summary> 
[ContentProperty("Then")] 
public class SwitchConverterCase 
{ 
    // case instances. 
    string _when; 
    object _then; 

    #region Public Properties. 
    /// <summary> 
    /// Gets or sets the condition of the case. 
    /// </summary> 
    public string When { get { return _when; } set { _when = value; } } 
    /// <summary> 
    /// Gets or sets the results of this case when run through a <see cref="SwitchConverter"/> 
    /// </summary> 
    public object Then { get { return _then; } set { _then = value; } } 
    #endregion 
    #region Construction. 
    /// <summary> 
    /// Switches the converter. 
    /// </summary> 
    public SwitchConverterCase() 
    { 
    } 
    /// <summary> 
    /// Initializes a new instance of the <see cref="SwitchConverterCase"/> class. 
    /// </summary> 
    /// <param name="when">The condition of the case.</param> 
    /// <param name="then">The results of this case when run through a <see cref="SwitchConverter"/>.</param> 
    public SwitchConverterCase(string when, object then) 
    { 
     // Hook up the instances. 
     this._then = then; 
     this._when = when; 
    } 
    #endregion 

    /// <summary> 
    /// Returns a <see cref="System.String"/> that represents this instance. 
    /// </summary> 
    /// <returns> 
    /// A <see cref="System.String"/> that represents this instance. 
    /// </returns> 
    public override string ToString() 
    { 
     return string.Format("When={0}; Then={1}", When.ToString(), Then.ToString()); 
    } 
} 

Наконец, для компонента TreeView, что вам требуется .. вы можете поставить даже другой DataGrid внутри каждой ячейки, чтобы достичь того уровня глубины вам требуется.

+0

Это выглядит, как это есть все, что я ищу. Я проверю это как можно скорее, спасибо! –

1

Я думаю, вы обнаружите, что стандартный WPF TreeView с некоторыми умными шаблонами будет делать трюк

+0

Я тоже посмотрю на это, спасибо :) –

Смежные вопросы