4

WPF では、いくつかの列が定義されたグリッドがあり、各列の幅は次のように DataGrid 列の幅にバインドされています。

<Grid.ColumnDefinitions>
   <ColumnDefinition Width="{Binding ElementName=dataGrid, Path=RowHeaderWidth}" />
   <ColumnDefinition Width="{Binding ElementName=Column0, Path=ActualWidth}" />
   <ColumnDefinition Width="{Binding ElementName=Column1, Path=ActualWidth}" />
   Etc.

<Controls:DataGrid BorderBrush="White"  ItemsSource="{Binding DataTable}"  
                   Name="datagrid1" Grid.Row="2" RowHeaderWidth="0">

    <Controls:DataGrid.Columns>
    <Controls:DataGridTextColumn  Header="Included"  Width="50" x:Name="Column0" />
    <Controls:DataGridTextColumn  Header="First" Width="100" x:Name="Column1" />
     Etc.

プログラムを実行して手動で列のサイズを変更すると、Grid 列のサイズが変更され (ShowGridLines = true)、特定の Grid 列に関連付けられた要素が適切に移動することがわかります。

ただし、データ グリッドとグリッド列をコードに追加しようとすると、バインディングが機能しません (バインディング エラーは発生しません)。次に例を示します。

 binding = new Binding()
 {
    Source = dataGrid.Columns[col],
    Path = new PropertyPath("ActualWidth"),
    Mode = BindingMode.OneWay, 
 };

 colDef.SetBinding(WidthProperty, binding);

他のバリエーション (ElementName = "DataGridColumn1"、Path = new PropertyPath("ActualWidth") など) を試しましたが、エラーが発生しない (バインディングがない) か、「バインディングのソースが見つかりません」エラーまたは BindingExpression パス エラーが発生します。

コードでバインディングを設定する方法があるはずです...?

4

3 に答える 3

6

私は答えを見つけました。この行:

 colDef.SetBinding(WidthProperty, binding);

次のように変更する必要があります:

 colDef.SetBinding(ColumnDefinition.WidthProperty, binding);
于 2009-05-28T06:09:16.587 に答える
0
DataGridTextColumn textColumn = new DataGridTextColumn();
textColumn.Width = DataGridLength.SizeToHeader;

他のオプションを得るためにグーグルDataGridLength....

于 2011-11-21T09:19:18.117 に答える
0

私のプロジェクトでは、私はこれが好きです-それを手に入れる前にそれを機能させるのに多くの問題があったので、言及する価値があると思いました:

    DataGridTextColumn c = new DataGridTextColumn
    {
          // Binding to my value (not directly related to the question)
          Binding = new Binding
          {
               Path = new PropertyPath(cd.Title + ".Value"),
               Mode = BindingMode.TwoWay
          }
     };

     // Binding the width 
     BindingOperations.SetBinding(c, DataGridTextColumn.WidthProperty, new Binding
     {
           Source = cd,                        // An INotifying object
           Path = new PropertyPath("Width"),   // A Property of that object
           Mode = BindingMode.TwoWay
      });
于 2015-10-15T10:02:21.873 に答える