簡體   English   中英

如何在代碼中綁定WPF網格列寬?

[英]How can I bind WPF Grid Column Width in code?

在WPF中,我有一個定義了多個列的Grid,每列的寬度都綁定到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列的元素相應地移動。

但是,當我嘗試在代碼中添加數據網格和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路徑錯誤。

必須有一種方法來設置代碼中的綁定...?

我找到了答案。 這一行:

 colDef.SetBinding(WidthProperty, binding);

應改為:

 colDef.SetBinding(ColumnDefinition.WidthProperty, binding);

在我的項目中我確實喜歡這個 - 認為值得一提,因為在我得到之前我遇到了很多問題:

    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
      });
DataGridTextColumn textColumn = new DataGridTextColumn();
textColumn.Width = DataGridLength.SizeToHeader;

谷歌DataGridLength獲得其他選擇....

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM