【问题标题】:C# WPF - how to move a comboxbox over a datagrid cell programmaticallyC# WPF - 如何以编程方式在数据网格单元格上移动组合框
【发布时间】:2020-03-08 07:48:00
【问题描述】:

我在 C# 中使用 WPF

我有一个 DataGrid,我需要在其中显示一个组合框。 我知道我可以通过将 DataGridComboBoxColumn 添加到 DataGrid 来做到这一点,但是我为该列中的每个单元格设置了组合框。

但我需要做的是只为列中的某些单元格显示一个组合框。 所以我尝试的是通过使用 Cell.PointToScreen() 和 TranslateTransform() 将 Combobox 移动到单击单元格的位置,在当前数据网格单元格上显示一个 Combobox (cboSelectToleranz):

所以这是我尝试过的(代码后面)但它不起作用(组合框从屏幕上消失...)

private void myDatagrid_onCurrentCellChanged(object sender, EventArgs e)
{
    if (!displayCombobox)  return;


    //get screen postion of cell that was clicked
    //
    var cellContent = myDatagrid.CurrentCell.Column.GetCellContent(myDatagrid.CurrentCell.Item);
    DataGridCell cell = cellContent.Parent as DataGridCell;
    Point Position = cell.PointToScreen(new Point(0, 0));


    //try to move a combobox over current cell 
    //
    var tt = new TranslateTransform();

    tt.X = Position.X; 
    tt.Y = Position.Y;

    cboSelectToleranz.RenderTransform = tt;

}

【问题讨论】:

    标签: c# wpf datagrid controls move


    【解决方案1】:

    您可以尝试使用 DataGridTemplateColumn。

    https://docs.microsoft.com/it-it/dotnet/api/system.windows.controls.datagridtemplatecolumn?view=netframework-4.8

    在数据模板中,您可以定义 ComboBox 并将其可见性绑定到模型的属性。

    【讨论】:

      【解决方案2】:

      您可以将DataGridTemplateColumnDataTemplateSelector 一起使用。定义您的模板,其中之一将是 ComboBox

      DataTemplateSelector 会根据绑定属性的值选择合适的模板:

      // example of custom type and simple DataTemplateSelector
      public class YourItemType
      { 
          public string Property { get; set; }
      }
      
      public class YourTemplateSelector : DataTemplateSelector
      {
          public DataTemplate TextTemplate { get; set; }
          public DataTemplate ComboTemplate { get; set; }
      
          public override DataTemplate SelectTemplate(object item, DependencyObject container)
          {
              return (item is YourItemType yourItem && yourItem.Property.Equals("condition here")) ? ComboTemplate : TextTemplate;
          }
      }
      
      <!--Somewhere in static resources-->
      <DataTemplate x:Key="comboTemplate">
          <ComboBox IsEditable='False'
                    ItemsSource='{Binding YourItemsSource}' SelectedItem='{Binding Property}'
                    Text='{Binding Property}' />
      </DataTemplate>
      
      <DataTemplate x:Key="textTemplate">
          <ComboBox Text='{Binding Property}' />
      </DataTemplate>
      
      <local:YourTemplateSelector x:Key='YourTemplateSelector'
                                  TextTemplate='{StaticResource textTemplate}'
                                  ComboTemplate='{StaticResource comboTemplate}' />
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-02
        • 2012-05-05
        • 1970-01-01
        • 1970-01-01
        • 2017-01-26
        • 2019-09-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多