2016-03-20 3 views
0

Я добавляю строки в сетку данных динамически, используя список как источник и источник.Отключение редактирования при динамическом добавлении их с помощью WPF

Однако я хочу отключить пользователя для редактирования некоторых ячеек сетки данных.

Как я могу сделать это простым способом?

Прикрепленные мой код:

/// <summary> 
    /// this class contain the data for the table in order to add the data for the table 
    /// </summary> 
    public class DataFroGrid 
    { 
     private string des; 
     /// <summary> 
     /// conatin the desction field for the data 
     /// </summary> 
     public string Description 
     { 
      get { return des; } 
      set { des = value; } 
     } 
     private string numberOfBytes; 
     /// <summary> 
     /// contain the number of byte for adding to the data 
     /// </summary> 
     public string NumberOfBytes 
     { 
      get { return numberOfBytes; } 
      set { numberOfBytes = value; } 
     } 

     private string value; 

     /// <summary> 
     /// contain the value for adding to the data 
     /// </summary> 
     public string Value 
     { 
      get { return this.value; } 
      set { this.value = value; } 
     } 

     public DataFroGrid() 
     { 
      des = ""; 
      numberOfBytes = ""; 
      value = ""; 
     } 
    } 

    private List<DataFroGrid> _ListForDataCommands; // a list for attached the data as a data source 

    public addQuestionMarkCommand(string[] description, int[] numberOfBytes ,string [] Value) 
    { 
     WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen; // start window in the middle of the screen 
     _ListForDataCommands = new List<DataFroGrid>(); 
     res = ""; // get the result values 
     InitializeComponent();    
     eUserClosed += addQuestionMarkCommand_eUserClosed; // create an event for closing the window. 

     // update the item source per the data that has been received 
     for (int i = 0; i < description.Length; i++) 
     { 
      DataFroGrid dfg = new DataFroGrid(); 
      dfg.Description = description[i]; 
      dfg.NumberOfBytes = numberOfBytes[i].ToString(); 
      dfg.Value = Value[i]; 
      _ListForDataCommands.Add(dfg);     
      //want to disable editing cell per data???? 
     } 

     dataGridCommand.ItemsSource = _ListForDataCommands;            
} 
+0

Было бы полезно, чтобы увидеть ваш XAML. Пожалуйста, отметьте это так, чтобы опубликовать некоторые другие идеи: http://stackoverflow.com/questions/3843331/how-to-make-wpf-datagridcell-readonly – Taterhead

ответ

0

Если вы хотите код позади решения, есть IsReadOnly собственности на DataGridColumn и вы можете установить, что в качестве обработчика событий для DataGrid.AutoGeneratingColumn события. Вот MSDN link for AutoGeneratingColumn event, что может быть полезно.

Вот фрагмент кода, который позволит сделать NumberOfBytes колонку только для чтения:

private void Grid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e) 
{ 
    if (e.Column.Header.ToString() == "NumberOfBytes") 
    {     
     e.Column.IsReadOnly = true; // Makes the column as read only 
    } 
} 
+0

, но что я хочу в какой-то строке? –

0

DataGridCell обладает свойством IsEnabled. Вы можете переопределить CellStyle и добавить привязку к свойству IsEnabled.

<DataGrid> 
     <DataGrid.CellStyle> 
      <Style TargetType="DataGridCell"> 
       <Setter Property="IsEnabled" Value="{Binding RelativeSource={RelativeSource Mode=Self}, Converter={local:IsEnabledConverter}}" /> 
      </Style> 
     </DataGrid.CellStyle> 
</DataGrid> 

Решение должно быть сделано в IsEnabledConverter:

public class IsEnabledConverter : MarkupExtension, IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     var cell = value as DataGridCell; 
     var rowData = cell.DataContext as DataFroGrid; // data object bound to the row 

     // you may analyze column info, row data here and make a decision 

     if (cell.Column.Header.ToString()=="ColumnName1") 
     {     
      return false; 
     } 

     return true; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     throw new NotSupportedException(); 
    } 

    public override object ProvideValue(IServiceProvider serviceProvider) 
    { 
     return this; 
    } 
}