Custom DataGrid column with a CellTemplate and binding

后端 未结 2 1561
醉酒成梦
醉酒成梦 2021-01-06 06:03

I need to create a reusable DataGrid column with a custom CellTemplate. This CellTemplate should, among other things, contain a TextBlock control to which I need to bind val

相关标签:
2条回答
  • 2021-01-06 06:24

    The question is pretty old, but i recently faced this issue myself. An Alternative to @Gregfr answer above is to write your custom DataGridColumn class. The following is what i have done for DatePicker Column:

     public class DataGridDatePickerColumn : DataGridBoundColumn
      {
        protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)
        {
          var datePicker = new DatePicker();
          datePicker.SetBinding(DatePicker.TextProperty, this.Binding);
          datePicker.SetBinding(DatePicker.SelectedDateProperty, this.Binding);
          return datePicker;
        }
    
        protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
        {
          var textBlock = new TextBlock();
          textBlock.SetBinding(TextBlock.TextProperty, this.Binding);
          return textBlock;
        }
      }
    

    Then i use it in one-line call in my xaml-pages like this:

    <h:DataGridDatePickerColumn IsReadOnly="False" Header="Some Date" Binding="{Binding SomeDate, StringFormat='dd.MM.yyyy'}" />
    

    In your case you could extend this C# Class by writing supporting functions that work with PreviewTextInput property and use regex expressions like [0-9]+ to control editing.

    0 讨论(0)
  • 2021-01-06 06:25

    I think the simplest thing to do is to create a customcontrol then use it like this:

                <DataGridTemplateColumn>
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <controls:CustomColumn Header="Name" Binding="{Binding Name}" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
    

    I did something similar yesterday, and it works pretty well

    0 讨论(0)
提交回复
热议问题