wpf使用滚动条动态地将项添加到stackpanel

时间:2017-11-16 22:05:55

标签: wpf grid scrollview stackpanel

我正在尝试创建两列控件。让我们说第一列有20个用户可以与之交互的标签或按钮,第二列有大约80个标签/按钮。我也喜欢滚动条。

当我添加scrollview时,我的第一列消失了。如何添加滚动条?

            InitializeComponent();
        Populate();
    }

    protected void Populate()
    {
        for (int i = 0; i <= (int) 20; i++)
        {
            Button l = new Button();
            l.Content = i;
            StyleSP.Children.Add(l);
        }


        for (int i = 100; i < 170; i++)
        {
            Button l = new Button();
            l.Content = i;
            IndustrySP.Children.Add(l);
        }
    }

WPF

<UserControl x:Class="Factor.Control.FactorList"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="700" d:DesignWidth="300" >
<Grid Height="300">

    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <ScrollViewer>
    <StackPanel Name="StyleSP" Background="Chocolate"  Grid.Column ="0" Height="300">

        </StackPanel>
        </ScrollViewer>
    <ScrollViewer>
        <StackPanel  Name="IndustrySP" Background="AliceBlue" Grid.Column="1" Height="300">

        </StackPanel>
    </ScrollViewer>
</Grid>

3 个答案:

答案 0 :(得分:0)

    <StackPanel Name="StyleSP" 
                Background="Chocolate"  
                Grid.Column ="0"
                Height="300"
                ScrollViewer.CanContentScroll="True"
                ScrollViewer.HorizontalScrollBarVisibility="Auto"
                ScrollViewer.VerticalScrollBarVisibility="Auto">

    </StackPanel>
    <StackPanel Name="IndustrySP" 
                Background="AliceBlue"  
                Grid.Column ="1"
                Height="300"
                ScrollViewer.CanContentScroll="True"
                ScrollViewer.HorizontalScrollBarVisibility="Auto"
                ScrollViewer.VerticalScrollBarVisibility="Auto">

    </StackPanel>

答案 1 :(得分:0)

我的问题是我忽略了将'Grid.Column'从StackPanel向上移动到ScrollViewer。

答案 2 :(得分:0)

我想您需要水平滚动条。

需要做两件事:

1。将属性IsReadOnly="True"添加到您的DataGrid

2。将MaxWidth="1200" VerticalScrollBarVisibility="Auto"添加到您的ScrollViewer

需要设置MaxWidth,您可以根据需要将1200更改为任何其他值。

<ScrollViewer MaxWidth="1200" VerticalScrollBarVisibility="Auto">
    <StackPanel  Name="IndustrySP" Background="AliceBlue" Grid.Column="1" Height="300">

    </StackPanel>
</ScrollViewer>