简体   繁体   中英

Binding programmatically generated DataGridTextColumn's Visibility property to a checkbox

I'm trying to bind the visibility property of a DataGridTextColumn to the IsChecked value of a combo box (cbIP). For most columns, I have solved the problem in XAML with lines like this:

<DataGridTextColumn Header="Time" Binding="{Binding MeasureTime}" Visibility="{Binding Source={x:Reference cbMeasureTime}, Path=IsChecked, Converter={StaticResource BoolToVisConverter}}"></DataGridTextColumn>

However, some columns regard values that are based on arrays of varying length (and therefore varying number of columns). This I have no problem creating in the code behind. The only problem is the visibility property. I have come this far:

private void Page_Loaded_1(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < ds.NumberOfIPValues; i++)
            {
                DataGridTextColumn col = new DataGridTextColumn() { Header = String.Format("IP #{0} (mV/V)", i + 1) };
                col.Binding = new Binding(String.Format("IP[{0}]",i));

                Binding b = new Binding("Visibility");
                b.Source = cbIP;
                b.Path = new PropertyPath(typeof(CheckBox).GetProperty("IsChecked"));
                b.Converter = new BoolToVisibilityConverter();

                BindingOperations.SetBinding(col, DataGridTextColumn.VisibilityProperty, b);

                ViewInTableDataGrid.Columns.Add(col);              
            }          
        }  

Needless to say, it doesn't work. I see the columns, but the checkbox doesnt work. (It works for the XAML-generated columns.

What do I do wrong?

Thanks in advance!

I work the other way -> Try This where the list of columns are used to generate the check boxes, and then toggle the visiblity..

<ItemsControl ItemsSource="{Binding Path=Columns, ElementName=dgSearchResult, NotifyOnTargetUpdated=True, NotifyOnSourceUpdated=True}" >
   <ItemsControl.ItemTemplate>
      <DataTemplate >
         <Grid>
          <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="5"/>
            <ColumnDefinition Width="Auto"/>
          </Grid.ColumnDefinitions>
             <CheckBox Content="{Binding Path=Header}" IsChecked="{Binding Path=Visibility, NotifyOnTargetUpdated=True, NotifyOnSourceUpdated=True, Mode=TwoWay, Converter={StaticResource BooleanToHiddenConvertor}}" />
          </Grid>
     </DataTemplate>
  </ItemsControl.ItemTemplate>

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