2014-01-10 5 views
1

Я связываться с Xceed DataGridControl (Community Edition) с AutoCreatedColumnsСвязующие свойств столбцов из Xceed DataGrid в ViewModel атрибута свойства

ObservableCollection<ItemViewModel> Items 

Я хотел бы отметить ReadOnly свойства Созданных столбцов на основе атрибута Editable на свойство viewmodel.

class ItemViewModel : ViewModelBase { 

    [Editable(false)] 
    public string Id { get; set; } 

    string _comment; 
    [Editable(true)] 
    public string Comment { 
     get { return _comment; } 
     set { 
       _comment = value; 
       NotifyOfPropertyChanged(() => Comment); 
     } 
    // Other properties ... 

} 

Возможно ли это? или есть ли другой способ, которым я мог бы подключиться к созданию столбца, чтобы проверить свойство, которое привязано и программно установлено ReadOnly?

ответ

1

Я считаю, что оптимальным решением является просто подключить к ItemsSourceChangeCompleted события, как это:

void _dataGrid_ItemsSourceChangeCompleted(object sender, EventArgs e) 
{ 
    DataGridControl control = (DataGridControl)sender; 
    Type itemType = control.ItemsSource.GetType().GenericTypeArguments[0]; 
    foreach (var col in control.Columns) 
    { 
     PropertyInfo propInfo = itemType.GetProperty(col.FieldName); 
     if (propInfo != null) 
     { 
      EditableAttribute editableAttribute = propInfo.GetCustomAttributes().OfType<EditableAttribute>().FirstOrDefault(); 
      col.ReadOnly = (editableAttribute == null || !editableAttribute.Value); 
     } 
     else 
     { 
      col.ReadOnly = false; 
     } 
    } 
} 

В качестве альтернативы, вы можете связать свойство клеток ReadOnly к редактируемом атрибута, как описано here.

Если вы знаете, какие столбцы вы хотите отобразить вы могли бы упростить решение выше и связать Колонном ReadOnly свойство как это:

public class EditableConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     if (value != null) 
     { 
      PropertyInfo propInfo = value.GetType().GenericTypeArguments[0].GetProperty(parameter.ToString()); 
      if (propInfo != null) 
      { 
       EditableAttribute editableAttribute = propInfo.GetCustomAttributes().OfType<EditableAttribute>().FirstOrDefault(); 
       return (editableAttribute == null || !editableAttribute.Value); 
      } 
     } 
     return false; 
    } 
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 
<xcdg:DataGridControl.Columns> 
    <xcdg:Column FieldName="Id" 
       ReadOnly="{Binding RelativeSource={RelativeSource Self}, 
        Path=DataGridControl.ItemsSource, 
        Converter={StaticResource EditableConverter}, ConverterParameter=Id}" /> 
    <xcdg:Column FieldName="Comment" 
       ReadOnly="{Binding RelativeSource={RelativeSource Self}, 
        Path=DataGridControl.ItemsSource, 
        Converter={StaticResource EditableConverter}, ConverterParameter=Comment}" /> 
</xcdg:DataGridControl.Columns> 

Но тогда, вы можете также отключить AutoCreateColumns и определить Columns самостоятельно в коде (или выключите AutoCreateItemProperties и создайте свой собственный DataGridCollectionViewSource, где вы установили каждый DataGridItemProperty.IsReadOnly соответственно).

+0

Спасибо! В этом случае я закончил жесткое кодирование столбцов в XAML, но это хорошая информация для будущего! –