简体   繁体   中英

Make particular column of datagrid a combobox when AutoGenerateColumns=“True”

I know this has been asked before but I still can't get it to work I am just testing things because I m new so I'm not using MVVM. I have a datagrid bound to an Observable Collection of entities The data binding works fine but I want to make one column a ComboBox on edit mode Which i achieved but i couldn't not bind that column , to the specific property of the entity.

Here's my Datagrid xaml :

        <DataGrid x:Name="dataGrid1"   IsSynchronizedWithCurrentItem="false"  ItemsSource="{Binding}"  RowHeaderWidth="0"  HorizontalScrollBarVisibility="Disabled"  HorizontalAlignment="Left" Margin="50.752,160.516,0,0" VerticalAlignment="Top" Height="Auto"  MaxHeight="200"  Width="395.429" RenderTransformOrigin="0.5,0.5" Background="#FFCFCFCF"  ColumnWidth="*" HorizontalGridLinesBrush="Black" VerticalGridLinesBrush="Black" RowBackground="#FFCFCFCF" AreRowDetailsFrozen="True" Style="{DynamicResource DataGridStyle2}" CellEditEnding="dataGrid1_CellEditEnding" CurrentCellChanged="dataGrid1_CurrentCellChanged" Grid.Column="1" Opacity="0" SelectionChanged="dataGrid1_SelectionChanged" AutoGeneratingColumn="dataGrid1_AutoGeneratingColumn" >
        <DataGrid.CellStyle>
            <Style TargetType="DataGridCell">
                <Setter Property="Block.TextAlignment" Value="Center"/>
                <Setter Property="Template" Value="{DynamicResource DataGridCellControlTemplate1}"/>
            </Style>
        </DataGrid.CellStyle>
        <DataGrid.Effect>
            <DropShadowEffect BlurRadius="20"/>
        </DataGrid.Effect>
        <DataGrid.RenderTransform>
            <TransformGroup>
                <ScaleTransform/>
                <SkewTransform/>
                <RotateTransform/>
                <TranslateTransform/>
            </TransformGroup>
        </DataGrid.RenderTransform>
        <DataGrid.ColumnHeaderStyle>
            <Style TargetType="{x:Type DataGridColumnHeader}">
                <Setter Property="Background" Value="{StaticResource PrimaryBrush}"/>
                <Setter Property="Foreground" Value="{DynamicResource PrimaryFont}" />
                <Setter Property="HorizontalContentAlignment" Value="Center" />
            </Style>
        </DataGrid.ColumnHeaderStyle>
        <DataGrid.Columns >

            <DataGridTemplateColumn x:Name="champ_delete" d:IsHidden="True" >
                <DataGridTemplateColumn.CellTemplate >
                    <DataTemplate>
                        <Button x:Name="delete" Content="Button" Width="30" Height="30" Style="{DynamicResource ButtonStyle12}" Click="supprime_Click"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>


        </DataGrid.Columns>




    </DataGrid>

And here is my MainWindow.xaml.cs code

/// <summary>
/// Interaction logic for MENU.xaml
/// </summary>
public partial class MENU : UserControl, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public MENU()
    {         
        this.InitializeComponent();            

        SContext = new Entities();

        ObsCollection = new ObservableCollection<PERFCONTENEUR>(SContext.PERFCONTENEUR.ToList());         

        DataContext = this;
        dataGrid1.ItemsSource = ObsCollection;
    }

    public BindingList<PERFCONTENEUR> Ji { get; set; }
    public ObservableCollection<PERFCONTENEUR> ObsCollection { get; set; }

    public Entities SContext;        

    private void dataGrid1_AutoGeneratingColumn(object sender, System.Windows.Controls.DataGridAutoGeneratingColumnEventArgs e)
    {

      if (e.PropertyName == "CLIENT")
        {
          var cb = new DataGridComboBoxColumn();

          e.Column.Header = "clients";
          cb.ItemsSource = (DataContext as ObservableCollection<PERFCONTENEUR>).ToList(); // I think the problem is here

          cb.SelectedValueBinding = new Binding("CLIENT");
          e.Column = cb;
         }  
    }
  }       

please refer below implementation.

<DataGrid  ItemsSource="{Binding Persons}" AutoGeneratingColumn="DataGrid_AutoGeneratingColumn"/>
 public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new ViewModel();
    }

    private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
        if (e.PropertyName == "FirstName")
        {
            DataGridComboBoxColumn cboclm = new DataGridComboBoxColumn();
            cboclm.Header = "First Name";
            cboclm.ItemsSource = (DataContext as ViewModel).Names;
            cboclm.SelectedValueBinding = new Binding("FirstName");
            e.Column = cboclm;
        } 
    }
}
 class ViewModel
{
    private ObservableCollection<Person> persons = new ObservableCollection<Person>();

    public ObservableCollection<Person> Persons
    {
        get { return persons; }
        set { persons = value; }
    }

    private ObservableCollection<string> names = new ObservableCollection<string>();

    public ObservableCollection<string> Names
    {
        get { return names; }
        set { names = value; }
    }   

    public ViewModel()
    {
        Person p = new Person();
        persons.Add(p);
        Names.Add("Test1");
        Names.Add("Test2");
    }

}

class Person
{
    private string firstName;

    public string FirstName
    {
        get { return firstName; }
        set { firstName = value; }
    }       

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM