以编程方式生成的扩展器,可滚动内容的大小调整为窗口

时间:2018-12-14 14:39:53

标签: c# wpf scroll window-resize expander

我正在寻找一种更好的方法,用following behavior.

来以编程方式生成窗口

即:可以通过编程初始化的扩展器列表,每个扩展器都包含可滚动内容,其内容大于窗口中可以显示的内容(在本例中为数据网格)。当扩展器被扩展时,其内容被限制为窗口的可用大小,同时允许所有其他扩展器被看到和操纵。另外,在任何给定时间只能打开一个扩展器。

此功能似乎在许多应用程序菜单中都非常有用,所以令我惊讶的是实现起来很困难。有比我更好的方法吗?

XAML(非常简单):

<Window x:Class="ExpanderScrollExample.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="200">
<Grid>
    <ItemsControl ItemsSource="{Binding Dict}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Grid Loaded="GridLoaded" ScrollViewer.CanContentScroll="False"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Expander Header ="{Binding Key, Mode=OneWay}" Expanded="Expander_Expanded" Collapsed="Expander_Collapsed">
                    <DataGrid ItemsSource="{Binding Path=Value}"/>
                </Expander>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Grid>

背后的代码(具有大部分魔力):

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace ExpanderScrollExample
{
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainWindowViewModel();
        }

        private void GridLoaded(object sender, RoutedEventArgs e)
        {
            Grid grid = sender as Grid;
            grid.LayoutUpdated += (s, e2) =>
            {
                var childCount = grid.Children.Count;
                int rowsToAdd = (childCount - grid.RowDefinitions.Count);
                for (int row = 0; row < rowsToAdd; row++)
                {
                    RowDefinition rowDefinition = new RowDefinition();
                    rowDefinition.Height = new GridLength(0, GridUnitType.Auto);
                    grid.RowDefinitions.Add(rowDefinition);
                }

                for (int i = 0; i < childCount; i++)
                {
                    var child = grid.Children[i] as FrameworkElement;
                    Grid.SetRow(child, i);
                }
            };
        }

        private void Expander_Expanded(object sender, RoutedEventArgs e)
        {
            ContentPresenter parentDataContext = VisualTreeHelper.GetParent(sender as DependencyObject) as ContentPresenter;
            Grid grid = VisualTreeHelper.GetParent(parentDataContext as DependencyObject) as Grid;
            grid.RowDefinitions[Grid.GetRow(parentDataContext)].Height = new GridLength(1, GridUnitType.Star);
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(grid); i++)
            {
                DependencyObject neighborDataContext = VisualTreeHelper.GetChild(grid, i);
                for (int j = 0; j < VisualTreeHelper.GetChildrenCount(neighborDataContext); j++)
                {
                    DependencyObject neighborExpander = VisualTreeHelper.GetChild(neighborDataContext, j);
                    if (neighborExpander is Expander && neighborExpander != sender)
                    {
                        ((Expander)neighborExpander).IsExpanded = false;
                        this.Collapse(neighborExpander as Expander);
                    }
                }
            }
        }

        private void Expander_Collapsed(object sender, RoutedEventArgs e)
        {
            this.Collapse(sender as Expander);
        }

        private void Collapse(Expander expander)
        {
            ContentPresenter parent = VisualTreeHelper.GetParent(expander as DependencyObject) as ContentPresenter;
            Grid grandparent = VisualTreeHelper.GetParent(parent as DependencyObject) as Grid;
            grandparent.RowDefinitions[Grid.GetRow(parent)].Height = new GridLength(0, GridUnitType.Auto);
        }
    }
}

ViewModel(仅用于数据生成)

using System.Collections.Generic;

namespace ExpanderScrollExample
{
    class MainWindowViewModel
    {
        public Dictionary<string, List<MyClass>> Dict { get; }

        public MainWindowViewModel()
        {
            Dict = new Dictionary<string, List<MyClass>>();
            for ( int i = 0; i < 5; i++ )
            {
                string key = "Header " + i.ToString();
                Dict[key] = new List<MyClass>();
                for ( int j = 0; j < 100; j++)
                {
                    Dict[key].Add(new MyClass(j, i*100 + j));
                }
            }
        }

        public class MyClass
        {
            public int Column1 {get; set;}
            public int Column2 { get; set; }

            public MyClass( int column1, int column2)
            {
                Column1 = column1;
                Column2 = column2;
            }
        }
    }
}

我通常也尝试使用MVVM模式进行确认,但在这种情况下无法这样做。

在网格中生成项目控件取自here. 我还考虑过按照this answer中的描述使用样式触发器来扩展/折叠和设置大小,但我想不出如何用扩展器绑定动态生成的行的好方法。

有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

1。在给定时间只有一个Expander展开

要确保在给定时间仅扩展一个Expander,可以创建一个Attached Behavior。我实现了一个以供参考。

ExpanderGroupBehavior(受RadioButton启发)

<Expander wpf:ExpanderGroupBehavior.GroupName="ExpanderGroup01" />

这可确保同一组内仅扩展一个Expander

2。扩大了Expander的可用空间

要实现这一目标,您可以创建自己的Panel来为您处理。 参见How to get controls in WPF to fill available space?https://docs.microsoft.com/en-us/dotnet/framework/wpf/controls/how-to-create-a-custom-panel-element