跟我一起学wpf(1)-布局

wpf常用的布局控件

 Canvas,DockPanel,Grid,StackPanel,WrapPane

1 Canvas是常用的画布容器,里面可以包含多个比如之前我写的3D效果的动画,都是用Canvas作为载体

  Canvas里有几个比较有用的方法

  Canvas.SetLeft,Canvas.SetRight,Canvas.SetTop

  与之相对的是Canvas.GetLeft之类

我最喜欢说一些不搭边的事儿,既然说到了坐标,我们就来更为详细的说一说坐标的事儿

<Window x:Class="StudyWpfWithMe.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">
    <Grid>
        <Canvas Name="canvas" Background="LemonChiffon">
            <TextBox Name="textBox" Width="300" Height="30"/>
        </Canvas>
    </Grid>
</Window>

你可以设置TextBox的位置,可以拖动,他会自动给你加一些属性

    <Grid>
        <Canvas Name="canvas" Background="LemonChiffon">
            <TextBox Name="textBox" Width="300" Height="30" Canvas.Left="58" Canvas.Top="60"/>
        </Canvas>
    </Grid>

我们加入MoveMouse事件

     private void Window_MouseMove(object sender, MouseEventArgs e)
        {
            var point=e.GetPosition(this);
            var textPoint=e.GetPosition(textBox);
            textBox.Text = string.Format("当前坐标是:{0},{1},textbox相对坐标是:{2},{3}", point.X, point.Y, textPoint.X, textPoint.Y);
        }

这里

e.GetPosition(this)是鼠标相对于界面最左边,
e.GetPosition(textBox);是鼠标相对于textbox的位置,是相对位置,以textbox来计算的,这就是坐标,挺有意思的事儿

基本的Canvas的最常用的大概就是这些了

2 Grid

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
        </Grid.RowDefinitions>
        
        <Grid.ColumnDefinitions>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Canvas Grid.Row="0" Grid.Column="0" Name="canvas" Background="LemonChiffon">
            <TextBox Name="textBox" Width="300" Height="30" Canvas.Left="58" Canvas.Top="60"/>
        </Canvas>
    </Grid>

Grid更多用于布局和重写某个模板样式时候,基本就是定义rowdefinition和coulumndefinition然后在控件里设置row和column

就是这样些东西

源代码:

下载

至于其他的三个,用的时候goole吧,没啥好说的

原文地址:https://www.cnblogs.com/fish124423/p/3693921.html