如何重用UI元素的组合?

时间:2019-06-27 10:04:50

标签: xaml uwp

在我的UWP xaml文件中,我需要像下面的ScrollViewer代码中那样重复使用StackPanel,该怎么做?

               <StackPanel Orientation="Vertical">
                    <Button Content="button1" Style="{StaticResource buttonStyle}">
                    </Button>
                    <Button Content="button1" Style="{StaticResource buttonStyle}">
                    </Button>
                    <Button Content="button1" Style="{StaticResource buttonStyle}">
                    </Button>
                </StackPanel>

...

       <ScrollViewer  
        Width="1920" 
        Height="1020" 
        HorizontalScrollMode="Enabled" 
        HorizontalScrollBarVisibility="Hidden" 
        VerticalScrollBarVisibility="Hidden">
            <StackPanel Orientation="Horizontal">
                <StackPanel Orientation="Vertical">
                    <Button Content="button1" Style="{StaticResource buttonStyle}">
                    </Button>
                    <Button Content="button1" Style="{StaticResource buttonStyle}">
                    </Button>
                    <Button Content="button1" Style="{StaticResource buttonStyle}">
                    </Button>
                </StackPanel>

                <StackPanel Orientation="Vertical">
                    <Button Content="button1" Style="{StaticResource buttonStyle}">
                    </Button>
                    <Button Content="button1" Style="{StaticResource buttonStyle}">
                    </Button>
                    <Button Content="button1" Style="{StaticResource buttonStyle}">
                    </Button>
                </StackPanel>

                ...

            </StackPanel>
        </ScrollViewer>

1 个答案:

答案 0 :(得分:0)

创建一个UserControl并在其中定义StackPanel

<UserControl
    x:Class="App1.MyUserControl1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App1"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300"
    d:DesignWidth="400">
    <StackPanel Orientation="Vertical">
        <Button Content="button1" Style="{StaticResource buttonStyle}">
        </Button>
        <Button Content="button1" Style="{StaticResource buttonStyle}">
        </Button>
        <Button Content="button1" Style="{StaticResource buttonStyle}">
        </Button>
    </StackPanel>
</UserControl> 

然后,您可以在UserControl中创建ScrollViewer的多个实例:

<ScrollViewer  
        Width="1920" 
        Height="1020" 
        HorizontalScrollMode="Enabled" 
        HorizontalScrollBarVisibility="Hidden" 
        VerticalScrollBarVisibility="Hidden">
    <StackPanel Orientation="Horizontal">
        <local:MyUserControl1 />
        <local:MyUserControl1 />
        <local:MyUserControl1 />
    </StackPanel>
</ScrollViewer>