C#WPF-如何以编程方式在数据网格单元上移动组合框

我在C#中使用WPF

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

但是我需要做的是只为列中的某些单元格显示一个Combox。 因此,我尝试通过使用Cell.PointToScreen()和TranslateTransform()将组合框移动到单击的单元格的位置来在当前数据网格单元格上显示组合框(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;

}
dibatian 回答:C#WPF-如何以编程方式在数据网格单元上移动组合框

您可以尝试使用DataGridTemplateColumn。

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

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

,

您可以将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}' />
本文链接:https://www.f2er.com/3116391.html

大家都在问