WPF的入门学习

环境的搭配

我们通过VS的官网来安装的VS2022,安装上C#的功能,这样就完成了环境的搭配

第一个wpf工程

打开vs2022,点击如图的创建新的工程。

点选WPF的项目

配置一个新的项目

这样就完成了项目的创建

项目结构

介绍一下大概的项目结构

在APP.XAml文件中,设置我们的窗体入口

界面的处理方式

  1. 内容添加

  2. XAML:微软公司为了构建应用程序用户界面而创建的一种新的"可扩展应用程序标记语言",提供了一种便于扩展和定位的语法来定义和程序逻辑分离的用户界面。

特点:

  • 定义应用程序的界面元素
  • 显式的声明WPF资源(样式、模板、动画等)
  • 可扩展性(自定义UI空间)
  • 集中关注于界面的设计和实现。

基础空间

textblock

通过工具箱拖动,拖出来textblock控件。

通过属性,就可以找到常见的一些属性

通过对应的事件,响应对应的代码

比较重要的布局

label控件

拥有跟textblock控件差不多的属性,事件和布局。

和textblock的区别
Lable的content属性为OBJECT类型

添加一个button对象在Lable控件中

cs文件中

public MainWindow()
{

    InitializeComponent();

    Button newButton = new Button();
    newButton.Content = "Click me";
    // 根据需要设置其他属性,例如宽度、高度等
    // newButton.Width = 100;
    // newButton.Height = 30;

    // 将新创建的 Button 赋值给 Label 的 Content
    myLabel.Content = newButton;
}

xaml文件

<Label x:Name="myLabel">
    <Label.Content>
        <Button Content="Click me" />
    </Label.Content>
</Label>

布局控件

布局属性和布局控件是不同的,布局属性用来做小范围的控制,布局控件大区域的划分。

常见的控件

  • Grid
  • StackPanel
  • WrapPanel
  • DockPanel
  • Canvas
  • UniformGrid
  1. Grid控件

定义行

Xaml语法

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
<Grid/>

定义列
Xaml语法

<Grid>
<Grid.ColumnDefinitions>
    <ColumnDefinition/>
    <ColumnDefinition/>
    <ColumnDefinition/>
    <ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid/>

给控件设置布局

 <TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Text="啊~我的妻,王氏宝钗!" VerticalAlignment="Top"
            Grid.Row="2" Grid.Column="1"/>
 <Label x:Name="myLabel" Grid.Row="1" Grid.Column="2">
     <Label.Content>
         <Button Content="Click me" />
     </Label.Content>
 </Label>
  1. StackPanel控件

类似堆栈的视图

控制方向的代码

 <StackPanel Orientation="Horizontal">
     <Button Content="Show Message" Click="Button_Click" Foreground="Red"/>
     <Button Content="Show Dialog" Click="Button_Click_1" Foreground="Pink"/>
 </StackPanel>

3. WrapPanel

类似于棋盘的排布,高度比较统一。当是水平分布的时候,会因为其中的任何一个影响行之间的高度,但是不会受到宽度的影响。(反之亦然)

```xaml
 <WrapPanel>
     <TextBlock Height="100" Width="100" Text="Hello World" Background="Red"/>
     <TextBlock Height="100" Width="100" Text="Hello World" Background="Green"/>
     <TextBlock Height="100" Width="100" Text="Hello World" Background="Blue"/>
     <TextBlock Height="100" Width="100" Text="Hello World" Background="Yellow"/>
     <TextBlock Height="100" Width="100" Text="Hello World" Background="Orange"/>
     <TextBlock Height="100" Width="100" Text="Hello World" Background="Purple"/>
     <TextBlock Height="150" Width="100" Text="Hello World" Background="Red"/>
     <TextBlock Height="100" Width="100" Text="Hello World" Background="Green"/>
     <TextBlock Height="100" Width="100" Text="Hello World" Background="Blue"/>
     <TextBlock Height="100" Width="100" Text="Hello World" Background="Yellow"/>
     <TextBlock Height="100" Width="100" Text="Hello World" Background="Orange"/>
     <TextBlock Height="100" Width="100" Text="Hello World" Background="Purple"/>
 </WrapPanel>
  1. DockPanel控件

停靠效果的布局控件

<DockPanel LastChildFill="false">
    <TextBlock  Text="Hello World" Background="Green" DockPanel.Dock="Top"/>
    <TextBlock  Text="Hello World" Background="Blue" DockPanel.Dock="Bottom"/>
    <TextBlock  Text="Hello World" Background="Yellow" DockPanel.Dock="Left"/>
    <TextBlock  Text="Hello World" Background="Orange" DockPanel.Dock="Right"/>
    
</DockPanel>
  1. Canvas控件

画布布局,都是从左边顶点开始的布局。

xaml

<Canvas>
        <TextBlock Width="100" Height="40" Text="Hello" Background="Gray" Margin="200,0,0,0"/>
        <TextBlock Width="100" Height="40" Text="Hello" Background="Orange" Margin="200,200,0,0"/>
        <TextBlock Width="100" Height="60" Text="Hello" Background="Red" Canvas.Left="300"/>
        <TextBlock Width="100" Height="40" Text="Hello" Background="Green" Canvas.Top="300" Canvas.Left="300"/>
        <TextBlock Width="100" Height="40" Text="Hello" Background="Gray" Canvas.Right="50" Canvas.Bottom="50"/>
        <TextBlock Width="100" Height="40" Text="Hello" Background="Gray" Canvas.Right="50" Canvas.Bottom="50" Canvas.Top="30" Canvas.Left="30" />
    </Canvas>
  1. InkCanvas控件

可编辑的画布布局控件

 <InkCanvas EditingMode="Select">
        <TextBlock Width="100" Height="40" Text="Hello" Background="Gray" Margin="200,0,0,0"/>
        <TextBlock Width="100" Height="40" Text="Hello" Background="Orange" Margin="200,200,0,0"/>
        <TextBlock Width="100" Height="60" Text="Hello" Background="Red" InkCanvas.Left="300"/>
        <TextBlock Width="100" Height="40" Text="Hello" Background="Green" InkCanvas.Top="300" InkCanvas.Left="300"/>
        <TextBlock Width="100" Height="40" Text="Hello" Background="Gray" InkCanvas.Right="50" InkCanvas.Bottom="50"/>
        <TextBlock Width="100" Height="40" Text="Hello" Background="Gray" InkCanvas.Right="50" InkCanvas.Bottom="50" InkCanvas.Top="30" InkCanvas.Left="30" />
    </InkCanvas>
  1. UniformGrid控件

UniformGrid【统一布局】,提供一种在网格(网格中的所有单元格都具有相同的大小)中排列内容的方法。

    <UniformGrid Columns="2" Rows="5">
        <TextBlock Text="Hello" Background="Gray"/>
        <TextBlock Text="Hello" Background="Orange"/>
        <TextBlock Text="Hello" Background="Red"/>
        <TextBlock Text="Hello" Background="Green"/>
        <TextBlock Text="Hello" Background="Gray"/>
        <TextBlock Text="Hello" Background="Orange"/>
        <TextBlock Text="Hello" Background="Red"/>
        <TextBlock Text="Hello" Background="Green"/>
        <TextBlock Text="Hello" Background="Gray"/>
        <TextBlock Text="Hello" Background="Orange"/>
        <TextBlock Text="Hello" Background="Red"/>
        <TextBlock Text="Hello" Background="Green"/>
        <TextBlock Text="Hello" Background="Gray"/>
        <TextBlock Text="Hello" Background="Orange"/>
        <TextBlock Text="Hello" Background="Red"/>
        <TextBlock Text="Hello" Background="Green"/>
        <TextBlock Text="Hello" Background="Gray"/>
        <TextBlock Text="Hello" Background="Orange"/>
        <TextBlock Text="Hello" Background="Red"/>
        <TextBlock Text="Hello" Background="Green"/>
        <TextBlock Text="Hello" Background="Gray"/>
        <TextBlock Text="Hello" Background="Orange"/>
        <TextBlock Text="Hello" Background="Red"/>
        <TextBlock Text="Hello" Background="Green"/>
        <TextBlock Text="Hello" Background="Gray"/>
        <TextBlock Text="Hello" Background="Orange"/>
        <TextBlock Text="Hello" Background="Red"/>
        <TextBlock Text="Hello" Background="Green"/>
    </UniformGrid>

button控件

xaml文件

    <Label x:Name="myLabel">
        <Label.Content>
            <Button Content="Click me" Click="Button_Click"/>
        </Label.Content>
    </Label>

cs文件

        public MainWindow()
        {
            InitializeComponent();

            Button newButton = new Button();
            newButton.Content = "Click me";
            newButton.Click += Button_Click; // 绑定点击事件
            myLabel.Content = newButton;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button button)
            {
                button.Content = "Title Changed!";
            }
        }

RepeatButton控件

它的主要目的是提供一种在用户按下并持有时会连续触发事件的行为。

<StackPanel>
    <RepeatButton Content="nihao" IsEnabled="True" Interval="500" Click="RepeatButton_Click"></RepeatButton>
</StackPanel>

cs文件

private void RepeatButton_Click(object sender, RoutedEventArgs e)
{
   Debug.WriteLine("RepeatButton_Click");
}

TextBox控件


<TextBox Width="300" TextWrapping="Wrap" Text="45r435r43t43t43t34t34t43tretg43t4t34t43tert43tert"
                 Height="50" ScrollViewer.VerticalScrollBarVisibility="Auto" Name="tb"/>

Password控件

  <PasswordBox Password="123456" PasswordChar="A" MaxLength="8" Name="pb" Foreground="#FFF10000"/>

richtext控件

<RichTextBox>
            <FlowDocument>
                <Paragraph>
                    Hello World!
                    <Run Foreground="Red" FontWeight="Bold" FontStyle="Italic">wef</Run>
                     wdf
                    <Hyperlink NavigateUri="https://www.baidu.com">ewrgwgtrbg</Hyperlink>
                     th
                </Paragraph>
                <Paragraph>
                    <Run>Hello</Run>
                </Paragraph>
            </FlowDocument>
        </RichTextBox>

image控件

显示图片用的控件

    <Grid.Background>
            <ImageBrush ImageSource="/Images/Logo.png"/>
        </Grid.Background>
        <Image Source="/Images/Logo.png" Height="50"/>

        <!--<Ellipse Width="50" Height="50">
            <Ellipse.Fill>
                <ImageBrush ImageSource="/Images/Logo.png" Stretch="UniformToFill"/>
            </Ellipse.Fill>
        </Ellipse>-->

radiobutton控件

        <Grid>
            <RadioButton Content="男" IsChecked="True" GroupName="A"/>
        </Grid>
        <Grid>
            <RadioButton Content="女" GroupName="A"/>
        </Grid>

        <RadioButton Content="身份证" IsChecked="True" GroupName="B"/>
        <RadioButton Content="护照" GroupName="B"/>

checkbox控件

       <CheckBox Content="苹果" IsChecked="True"/>
        <CheckBox Content="菠萝"/>
        <CheckBox Content="凤梨" IsChecked="{x:Null}"/>

slider控件

xaml文件

    <TextBlock Name="tb"/>
        <Slider Value="5" ValueChanged="Slider_ValueChanged" 
                Minimum="-10" Maximum="100" TickFrequency="10" TickPlacement="Both"
                IsSnapToTickEnabled="True"/>

cs文件

    <TextBlock Name="tb"/>
        <Slider Value="5" ValueChanged="Slider_ValueChanged" 
                Minimum="-10" Maximum="100" TickFrequency="10" TickPlacement="Both"
                IsSnapToTickEnabled="True"/>

progressbar控件

    <TextBlock Name="tb"/>
        <Slider Value="5" ValueChanged="Slider_ValueChanged" 
                Minimum="-10" Maximum="100" TickFrequency="10" TickPlacement="Both"
                IsSnapToTickEnabled="True"/>

combox控件

 <ComboBox Width="200" SelectedIndex="2" SelectionChanged="ComboBox_SelectionChanged">
            <ComboBoxItem Content="---请选择---"/>
            <ComboBoxItem Content="AAA"/>
            <ComboBoxItem Content="BBB"/>
            <ComboBoxItem Content="CCC"/>
            <ComboBoxItem Content="DDD"/>
        </ComboBox>
        <ComboBox Width="200" Name="comboBox" SelectedIndex="0">
        </ComboBox>

listbox控件

  <TextBlock Name="tb"/>
        <ListBox Name="listBox" SelectionMode="Single" SelectionChanged="listBox_SelectionChanged">
            <!--<ListBoxItem Content="AAAA"/>
            <ListBoxItem Content="BBBB"/>
            <ListBoxItem Content="CCCC"/>
            <ListBoxItem Content="DDDD"/>
            <ListBoxItem Content="EEEE"/>
            <ListBoxItem Content="FFFF"/>-->
        </ListBox>

 private void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            tb.Text = (sender as ListBox).SelectedItem.ToString();
        }

listview控件

员工类

public class Employee
    {
        public bool IsSelected { get; set; }
        public string Name { get; set; }
        public string Department { get; set; }
        public int Age { get; set; }

        public string Gender { get; set; }
    }
<ListView Grid.Row="1" Name="lv">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="员工名称" Width="100" DisplayMemberBinding="{Binding Name}"/>
                    <GridViewColumn Header="部门" Width="100" DisplayMemberBinding="{Binding Department}"/>
                    <GridViewColumn Header="年龄" Width="100" DisplayMemberBinding="{Binding Age}"/>
                </GridView>
            </ListView.View>
        </ListView>
List<Employee> employees = new List<Employee>();
            employees.Add(new Employee() { Name = "AAA", Department = "D-1", Age = 19, Gender = "女" });
            employees.Add(new Employee() { IsSelected = true, Name = "BBB", Department = "D-2", Age = 20 });
            employees.Add(new Employee() { Name = "CCC", Department = "D-3", Age = 21, Gender = "男" });
            this.lv.ItemsSource = employees;

dataGrid控件

 List<Employee> employees = new List<Employee>();
            employees.Add(new Employee() { Name = "AAA", Department = "D-1", Age = 19, Gender = "女" });
            employees.Add(new Employee() { IsSelected = true, Name = "BBB", Department = "D-2", Age = 20 });
            employees.Add(new Employee() { Name = "CCC", Department = "D-3", Age = 21, Gender = "男" });
            this.lv.ItemsSource = employees;


            this.dg.ItemsSource = employees;
            this.dgcb.ItemsSource = new List<string> { "男", "女" };
DataGrid Grid.Row="2" Name="dg" AutoGenerateColumns="False" CanUserAddRows="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="员工名称" Width="100" Binding="{Binding Name}"/>
                <DataGridTextColumn Header="部门" Width="100" Binding="{Binding Department}"/>
                <DataGridTextColumn Header="年龄" Width="100" Binding="{Binding Age}"/>
                <DataGridCheckBoxColumn Header="勾选" Binding="{Binding IsSelected}"/>
                <DataGridComboBoxColumn Header="下拉列表" SelectedItemBinding="{Binding Gender}" x:Name="dgcb">
                </DataGridComboBoxColumn>

                <DataGridTemplateColumn Header="自定义" Width="100">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Grid>
                                <TextBlock Text="{Binding Name}"/>
                                <Image Source="images/logo.png"/>
                            </Grid>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                    <DataGridTemplateColumn.CellEditingTemplate>
                        <DataTemplate>
                            <TextBox Text="{Binding Name}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellEditingTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>

tabcontroler控件

xaml

 <TabControl>
            <TabItem Header="AAAA">
                <TextBlock Text="Hello AAA"/>
            </TabItem>
            <TabItem Header="BBBB">
                <Button Content="Hello BBB"/>
            </TabItem>
            <TabItem>
                <TabItem.Header>
                    <StackPanel Orientation="Horizontal">
                        <Image Source="images/logo.png" Width="20"/>
                        <TextBlock Text="CCCC"/>
                        <Button Content="X"/>
                    </StackPanel>
                </TabItem.Header>
            </TabItem>
            <TabItem Header="DDDD"/>
            <TabItem Header="EEEE"/>
        </TabControl>

xaml

        <Menu Grid.Row="1" Height="30" VerticalAlignment="Top">
            <MenuItem Header="文件(_F)">
                <MenuItem Header="新建(_N)" Click="MenuItem_Click">
                    <MenuItem.Icon>
                        <Image Source="images/logo.png"/>
                    </MenuItem.Icon>
                </MenuItem>
                <MenuItem Header="打开"/>
                <Separator/>
                <MenuItem Header="添加"/>
            </MenuItem>
            <MenuItem Header="编辑">
                <MenuItem Header="剪切"/>
                <Separator/>
                <MenuItem Header="复制"/>
                <MenuItem Header="粘贴"/>
            </MenuItem>
            <MenuItem Header="视图"/>
        </Menu>

        <Border Background="Orange" Width="100" Height="30" Grid.Row="1">
            <Border.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="文件(_F)">
                        <MenuItem Header="新建(_N)" Click="MenuItem_Click">
                            <MenuItem.Icon>
                                <Image Source="images/logo.png"/>
                            </MenuItem.Icon>
                        </MenuItem>
                        <MenuItem Header="打开"/>
                        <Separator/>
                        <MenuItem Header="添加"/>
                    </MenuItem>
                    <MenuItem Header="编辑">
                        <MenuItem Header="剪切"/>
                        <Separator/>
                        <MenuItem Header="复制"/>
                        <MenuItem Header="粘贴"/>
                    </MenuItem>
                    <MenuItem Header="视图"/>
                </ContextMenu>
            </Border.ContextMenu>
        </Border>

treeView控件


     <TreeView Grid.Row="2" SelectedItemChanged="TreeView_SelectedItemChanged"
                  Name="tv">
            <TreeViewItem Header="学生" IsExpanded="True">
                <TreeViewItem Header="一年级" IsExpanded="True">
                    <TreeViewItem Header="AAA"/>
                    <TreeViewItem Header="BBB"/>
                    <TreeViewItem Header="CCC"/>
                </TreeViewItem>
                <TreeViewItem Header="二年级"/>
                <TreeViewItem Header="三年级"/>
            </TreeViewItem>
            <TreeViewItem Header="老师">
                <TreeViewItem Header="AAA"/>
                <TreeViewItem Header="BBB"/>
                <TreeViewItem Header="CCC"/>
            </TreeViewItem>
        </TreeView>

cs

private void TreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            var item = (sender as TreeView).SelectedItem as TreeViewItem;
        }

Calender控件

<Calendar SelectedDate="10/15/2022" DisplayDate="4/25/2022"
                  DisplayDateStart="4/2/2022" DisplayDateEnd="12/10/2022"/>


        <Calendar Grid.Row="1" SelectionMode="MultipleRange"
                  xmlns:sys="clr-namespace:System;assembly=mscorlib">
            <Calendar.BlackoutDates>
                <CalendarDateRange Start="4/3/2022" End="4/10/2022"/>
                <CalendarDateRange Start="5/3/2022" End="5/20/2022"/>
            </Calendar.BlackoutDates>
            <Calendar.SelectedDates>
                <sys:DateTime>11/10/2022</sys:DateTime>
                <sys:DateTime>11/12/2022</sys:DateTime>
                <sys:DateTime>11/18/2022</sys:DateTime>
                <sys:DateTime>11/8/2022</sys:DateTime>
            </Calendar.SelectedDates>
        </Calendar>

dataPicker控件

<DatePicker Grid.Row="2" Height="30" Width="170"
                    SelectedDate="2022-12-01"
                    DisplayDateStart="4/2/2022" DisplayDateEnd="12/10/2022"
                    SelectedDateFormat="Short"
                    FirstDayOfWeek="Sunday"></DatePicker>

savedialog和opendialog

  <StackPanel>
      <Button Content="open" Click="Button_Click" ></Button>
      <Button Content="save" Click="Button_Click_1"></Button>
  </StackPanel>
 private void Button_Click(object sender, RoutedEventArgs e)
 {
     OpenFileDialog openFileDialog = new OpenFileDialog();
     openFileDialog.Filter = "Sql 文件(*.sql)|*.sql|所有文件(*.*)|*.*";
     //openFileDialog.FilterIndex= 1;
     openFileDialog.Multiselect = true;// 允许多选
     if (openFileDialog.ShowDialog() == true)
     {
         //var file = openFileDialog.FileName;
         //openFileDialog.FileNames

         // 进行文件内容读取 
     }

 }

 private void Button_Click_1(object sender, RoutedEventArgs e)
 {
     SaveFileDialog saveFileDialog = new SaveFileDialog();
     saveFileDialog.Filter = "Sql 文件(*.sql)|*.sql|所有文件(*.*)|*.*";
     if (saveFileDialog.ShowDialog() == true)
     {
         // 获取保存文件路径 
         var fn = saveFileDialog.FileName;

         // 文件内容写入
     }
 }

border控件和Expander控件

<Border Background="Gray" Width="50" Height="50" 
                BorderBrush="Red" BorderThickness="3"
                CornerRadius="5"/>
            <Expander Header="WPF零基础" IsExpanded="True">
                <StackPanel>
                    <Button Content="第一课"/>
                    <Button Content="第一课"/>
                    <Button Content="第一课"/>
                </StackPanel>
            </Expander>
            <Expander Header="WPF零基础">
                <StackPanel>
                    <Button Content="第一课"/>
                    <Button Content="第一课"/>
                    <Button Content="第一课"/>
                </StackPanel>
            </Expander>

GroupBox和ViewBox

 <GroupBox Header="WPF">
     <Button Content="第二课"/>
 </GroupBox>
 <GroupBox Header=".NET">
     <Button Content="第二课"/>
 </GroupBox>

 <Viewbox StretchDirection="Both" >
     <Border Background="Orange" Width="60" Height="60">
         <TextBlock Text="Zhaoxi"/>
     </Border>
 </Viewbox>

dispather控件

            <TextBox Text="Hello" Name="tb"/>
            <Button Content="Button" Click="Button_Click"/>

cs文件


            Task.Run(async () =>
            {
                try
                {
                    var value = 200;
                    await Task.Delay(2000);// 请求WebApi
                                           // 给TextBox赋值 
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        this.tb.Text = value.ToString();
                    }));
                }
                catch (Exception ex)
                {

                }
            });

posted @ 2024-11-06 18:36  飘雨的河  阅读(11)  评论(0编辑  收藏  举报