WPF WrapPanel与Grid布局

Posted 唐宋元明清的博客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WPF WrapPanel与Grid布局相关的知识,希望对你有一定的参考价值。

本节讲述布局,顺带加点样式给大家看看~单纯学布局,肯定是枯燥的~哈哈

那如上界面,该如何设计呢?

1、一些布局元素经常用到.Grid StackPanel Canvas WrapPanel等。如上这种布局,在子元素数量未知的情况下,我们应该使用WrapPanel或者StackPanel来布局,子元素会自己换行。

2、然后每一行的元素中,第一个要居左,第二个要居中,第三个要居要。这个应该通过Grid来布局,添加三列,然后对应的元素在每列中设置水平方向。

下面是代码:

1、界面:

<Window x:Class="WpfApplication16.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" Loaded="MainWindow_OnLoaded" Background="CornflowerBlue">
   
    <Grid>
        <ScrollViewer Margin="30,0" Height="200" Template="{StaticResource ScrollViewerControlTemplate1}">
            <StackPanel x:Name="SpElementList"></StackPanel>
        </ScrollViewer>
    </Grid>
</Window>

其中ScrollViewer样式:

    <Style x:Key="ScrollBarPageButton" TargetType="{x:Type RepeatButton}">
        <Setter Property="SnapsToDevicePixels" Value="True" />
        <Setter Property="OverridesDefaultStyle" Value="true" />
        <Setter Property="IsTabStop" Value="false" />
        <Setter Property="Focusable" Value="false" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type RepeatButton}">
                    <Border Background="Transparent" />
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <Style x:Key="ScrollBarThumb" TargetType="{x:Type Thumb}">
        <Setter Property="SnapsToDevicePixels" Value="True" />
        <Setter Property="OverridesDefaultStyle" Value="true" />
        <Setter Property="IsTabStop" Value="false" />
        <Setter Property="Focusable" Value="false" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Thumb}">
                    <Border CornerRadius="2" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="1" />
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <ControlTemplate x:Key="VerticalScrollBar" TargetType="{x:Type ScrollBar}">
        <Grid>
            <Border CornerRadius="2" Width="0.5" Background="#FF046BFF" />
            <Track x:Name="PART_Track" IsDirectionReversed="true">
                <Track.DecreaseRepeatButton>
                    <RepeatButton Style="{StaticResource ScrollBarPageButton}" Command="ScrollBar.PageUpCommand" />
                </Track.DecreaseRepeatButton>
                <Track.Thumb>
                    <Thumb Style="{StaticResource ScrollBarThumb}" Margin="4,0,4,0" Background="DodgerBlue"></Thumb>
                </Track.Thumb>
                <Track.IncreaseRepeatButton>
                    <RepeatButton Style="{StaticResource ScrollBarPageButton}" Command="ScrollBar.PageDownCommand" />
                </Track.IncreaseRepeatButton>
            </Track>
        </Grid>
    </ControlTemplate>

    <ControlTemplate x:Key="ScrollViewerControlTemplate1" TargetType="{x:Type ScrollViewer}">
        <Grid x:Name="Grid" Background="{TemplateBinding Background}">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <Rectangle x:Name="Corner" Grid.Column="1" Fill="{DynamicResource {x:Static SystemColors.ControlBrushKey}}" Grid.Row="1"/>
            <ScrollContentPresenter x:Name="PART_ScrollContentPresenter" CanContentScroll="{TemplateBinding CanContentScroll}" CanHorizontallyScroll="False" CanVerticallyScroll="False" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" Grid.Column="0" Margin="{TemplateBinding Padding}" Grid.Row="0"/>
            <ScrollBar x:Name="PART_VerticalScrollBar" AutomationProperties.AutomationId="VerticalScrollBar" Cursor="Arrow" Grid.Column="1" 
                            Maximum="{TemplateBinding ScrollableHeight}" Minimum="0" Grid.Row="0" Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}" 
                            Value="{Binding VerticalOffset, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}" ViewportSize="{TemplateBinding ViewportHeight}" 
                            Template="{StaticResource VerticalScrollBar}"/>
            <ScrollBar x:Name="PART_HorizontalScrollBar" AutomationProperties.AutomationId="HorizontalScrollBar" Cursor="Arrow" Grid.Column="0" Maximum="{TemplateBinding ScrollableWidth}" Minimum="0" Orientation="Horizontal" Grid.Row="1" Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}" Value="{Binding HorizontalOffset, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}" ViewportSize="{TemplateBinding ViewportWidth}"/>
        </Grid>
    </ControlTemplate>
View Code

CheckBox样式:

    <Style x:Key="CheckBoxStyle" TargetType="{x:Type CheckBox}">
        <Setter Property="SnapsToDevicePixels" Value="true" />
        <Setter Property="OverridesDefaultStyle" Value="False" />
        <Setter Property="FocusVisualStyle" Value="{DynamicResource CheckBoxFocusVisual}" />
        <Setter Property="Height" Value="25"/>
            <Setter Property="IsChecked" Value="{Binding IsChecked}"/>
        <Setter Property="Margin" Value="0,20"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="CheckBox">
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>
                        <Grid Height="{TemplateBinding Height}" Width="{TemplateBinding Height}">
                            <Rectangle x:Name="CheckBoxRectangle" Fill="LightSkyBlue" Opacity="0.3" RadiusY="5" RadiusX="5"/>
                            <Rectangle x:Name="CheckBoxRectangleOut" Stroke="#FF06DAD1" StrokeThickness="1" RadiusY="5" RadiusX="5"/>
                            <Grid x:Name="CheckedMark" Width="20" Height="20" Visibility="Collapsed">
                                <Path SnapsToDevicePixels="False" StrokeThickness="3" Data="M1,9 L10,17" Stroke="White"/>
                                <Path SnapsToDevicePixels="False" StrokeThickness="3" Data="M8,17 L20,4" Stroke="White"/>
                            </Grid>
                        </Grid>
                        <TextBlock Grid.Column="1" Text="{Binding Name}" FontSize="18" Foreground="White" VerticalAlignment="Center" Margin="14,0,0,0"/>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsChecked" Value="True">
                            <Setter TargetName="CheckedMark" Property="Visibility" Value="Visible"></Setter>
                            <Setter TargetName="CheckBoxRectangle" Property="Fill" Value="#FF00A8E0"></Setter>
                            <Setter TargetName="CheckBoxRectangle" Property="Opacity" Value="1"></Setter>
                            <Setter TargetName="CheckBoxRectangleOut" Property="Stroke" Value="Transparent"></Setter>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
View Code

 

2、后台代码

用C#语言添加控件:

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        public List<CheckDataModel> Datas = new List<CheckDataModel>()
        {
            new CheckDataModel(){IsChecked = true,Name="C#"},new CheckDataModel(){IsChecked = true,Name="Java"},new CheckDataModel(){IsChecked = true,Name="Python"},
            new CheckDataModel(){IsChecked = true,Name="VB.Net"},new CheckDataModel(){IsChecked = true,Name="php"},new CheckDataModel(){IsChecked = true,Name="WPF"},
            new CheckDataModel(){IsChecked = true,Name="Silverlight"},new CheckDataModel(){IsChecked = true,Name="Winform"},new CheckDataModel(){IsChecked = true,Name="WebForm"},
            new CheckDataModel(){IsChecked = true,Name="MVC"},new CheckDataModel(){IsChecked = true,Name="ios"},new CheckDataModel(){IsChecked = true,Name="html"},
            new CheckDataModel(){IsChecked = true,Name="Css"},new CheckDataModel(){IsChecked = true,Name="Ruby"},
        };
        private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
        {
            int index = 0;
            Grid grid = null;
            foreach (var data in Datas)
            {
                int value = index%3;
                if (value==0)
                {
                    grid=new Grid();
                    grid.ColumnDefinitions.Add(new ColumnDefinition());
                    grid.ColumnDefinitions.Add(new ColumnDefinition());
                    grid.ColumnDefinitions.Add(new ColumnDefinition());
                    SpElementList.Children.Add(grid);
                }
                
                var checkBox=new CheckBox();
                checkBox.Style = (Style) this.Resources["CheckBoxStyle"];
                checkBox.HorizontalAlignment = HorizontalAlignment.Left;
                checkBox.DataContext = data;
                Grid.SetColumn(checkBox,value);
                grid.Children.Add(checkBox);
                index++;
            }
        }
    }

    public class CheckDataModel
    {
        public string Name { get; set; }
        public bool IsChecked { get; set; }
    }
View Code

下面是VB语言(因为最近在学VB,就献丑一下。VB,其实VB和C#差不多)

Class MainWindow
    Public Datas As New List(Of CheckDataModel)
    Private Sub MainWindow_OnLoaded(sender As Object, e As RoutedEventArgs)
        Datas.Add(New CheckDataModel())
        Datas.Add(New CheckDataModel())
        Datas.Add(New CheckDataModel())
        Datas.Add(New CheckDataModel())
        Datas.Add(New CheckDataModel())
        Datas.Add(New CheckDataModel())
        Datas.Add(New CheckDataModel())
        Datas.Add(New CheckDataModel())
        Datas.Add(New CheckDataModel())
        Datas.Add(New CheckDataModel())
        Datas.Add(New CheckDataModel())
        Datas.Add(New CheckDataModel())
        Datas.Add(New CheckDataModel())
        Datas.Add(New CheckDataModel())
        Dim grid As Grid
        Dim index = 0
        For i As Integer = 0 To 10
            Dim value = index Mod 3
            If value = 0 Then
                grid = New Grid()
                grid.ColumnDefinitions.Add(New ColumnDefinition())
                grid.ColumnDefinitions.Add(New ColumnDefinition())
                grid.ColumnDefinitions.Add(New ColumnDefinition())
                SpElementList.Children.Add(grid)
            End If

            Dim checkBox = New CheckBox()
            checkBox.HorizontalAlignment = HorizontalAlignment.Left
            checkBox.Style = Resources.Item("CheckBoxStyle")
            checkBox.DataContext = Datas.Item(index)
            grid.SetColumn(checkBox, value)
            grid.Children.Add(checkBox)
            index += 1
        Next
    End Sub

End Class
Public Class CheckDataModel
    Private _name As String = "AAAAA"
    Public Property Name() As String
        Get
            Return _name
        End Get
        Set(value As String)
            _name = value
        End Set
    End Property

    Public Property IsChecked As Boolean
End Class
View Code

 

以上是关于WPF WrapPanel与Grid布局的主要内容,如果未能解决你的问题,请参考以下文章

WPF入门教程系列七——布局之WrapPanel与StackPanel

WPF布局控件与子控件的HorizontalAlignment/VerticalAlignment属性之间的关系

页面布局-Grid,StackPanel,DockPanel,WrapPanel

2021-08-17 WPF控件专题 Grid 控件详解

WPF教程三;布局之WrapPanel面板

WPF线段式布局的一种实现