将GridSplitter添加到动态创建的网格行中?

时间:2017-04-25 11:23:56

标签: c# wpf xaml wpf-controls

我正在开发一个具有分层可选树和视图的视图。 ItemsControl绑定到一组图表。这些图表在运行时根据用户选择进行解析。我希望图表能够垂直拉伸。分享所有可用空间。

我使用Rachel Lim's class在运行时使用ItemsControl ItemsPanelTemplate中的附加属性动态解析网格中的行。这按预期工作,图表共享可用空间

 <ItemsControl Grid.Row="1"  
      x:Name="TimeSeriesCharting"                                                                                          
          ItemsSource="{Binding TimeSeriesChartViewModels}">
                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <Grid helpers:GridHelpers.RowCount="{Binding RowCount}"
                                  helpers:GridHelpers.StarRows="0,1,2,3">
                            </Grid>
                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>

                    <!-- ItemContainerStyle -->
                    <ItemsControl.ItemContainerStyle>
                        <Style>
                <Setter Property="Grid.Row" Value="{Binding RowIndex}"/>
             </Style>
         </ItemsControl.ItemContainerStyle>                        
 </ItemsControl>

我现在想在所述网格的每一行中添加GridSplitter。在添加行定义的网格助手类中,我尝试添加GridSplitter但是当尝试操纵grid.Children集合时,它会抛出InvalidOperationException - 无法显式修改用作ItemsPanel的Panel的Children集合对于ItemsControl。 ItemsControl为Panel生成子元素。

   public static void RowCountChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
      if (!(obj is Grid) || (int)e.NewValue < 0)
      {
        return;
      }

      Grid grid = (Grid)obj;
      grid.RowDefinitions.Clear();

      for (int i = 0; i < (int)e.NewValue; i++)
       {
         grid.RowDefinitions.Add(new RowDefinition()
          {
            Height = GridLength.Auto
          });

          SetStarRows(grid);
         }

            grid.Children.Clear();

            for (int i = 0; i < grid.RowDefinitions.Count; i++)
            {
                GridSplitter gridSplitter = new GridSplitter();
                gridSplitter.SetResourceReference(FrameworkElement.StyleProperty, "HorizontalGridSplitterStyle");
                Grid.SetRow(gridSplitter, i);
                grid.Children.Add(gridSplitter);
            }        
        }

我假设在这种情况下使用ItemsControl存在问题。这里有更好的模式吗?将自定义网格写为独立用户控件可能吗?

0 个答案:

没有答案
相关问题