zl程序教程

您现在的位置是:首页 >  .Net

当前栏目

WPF内容控件以及数据绑定

2023-04-18 15:20:12 时间

WPF绑定数据

使⽤ Binding 对象建⽴绑定,且每个绑定通常具有四个组件:绑定⽬标、⽬标属性、绑定源以及指向要使⽤的源值的路径。

第一种绑定方式(在前台绑定):

过程:定义一个字典资源<Grid.Resources> 设置key和值(绑定的类)——>上下文<Grid.DataContext>绑定字典资源 <Binding Source="{StaticResource myDataSource}"/>关联类 ——>绑定类中的属性

DataBind.xaml:

<Window x:Class="Wang.Wpf.DataBinding.DataBind"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Wang.Wpf.DataBinding"
        xmlns:c="clr-namespace:Wang.Wpf.Entity" 
        mc:Ignorable="d"
        Title="DataBind" Height="450" Width="800">
    <Grid>        
        <Grid.Resources>
            <!--
               <Grid.Resources>是个资源字典  key 为myDataSource   value  为MyData类
                    (Resources是获取或设置本地定义的资源字典)
            -->
            <c:MyData x:Key="myDataSource"/> 
        </Grid.Resources>

        <Grid.DataContext>
            <!--            
            DataContext 获取或设置元素参与数据绑定时的数据上下文
            Binding  source 绑定资源
            StaticResource 静态资源  myDataSource 加载字典项             
            -->
            <Binding Source="{StaticResource myDataSource}"/>
        </Grid.DataContext>
        
        <!--
        按钮背景绑定的路径为类中的属性
        -->
        <Button Background="{Binding Path=ColorName}" 
                Width="{Binding Path=BuWidte}" Height="30">不可数的</Button> 
    </Grid>
</Window>

MyData.cs

namespace Wang.Wpf.Entity
{
    class MyData
    {
        private string colorName = "green";
        private int buWidte = 350;
        /// <summary>
        /// colorName属性的默认值为“red”,ctrl+r+e,快速封装字段
        /// </summary>
        public string ColorName { get => colorName; set => colorName = value; }
        public int BuWidte { get => buWidte; set => buWidte = value; }
    }
}

第二种绑定方式(在后台绑定):

DataBind.xaml中设置窗口刚加载时的事件Title="DataBind" Height="450" Width="800" Loaded="Window_Loaded">

 <Label Name="MyLabel" Content="{Binding Path=Title}" FontSize="30" FontWeight="Medium"/>
  Content取的值是绑定MyData类中的Title属性的值。

MyData.cs

space Wang.Wpf.Entity
{
    class MyData
    {
        private string colorName = "green";
        private int buWidte = 350;
        /// <summary>
        /// colorName属性的默认值为“red”,ctrl+r+e,快速封装字段
        /// </summary>
        public string ColorName { get => colorName; set => colorName = value; }
        public int BuWidte { get => buWidte; set => buWidte = value; }
        public string Title { get; set; }
    }

DataBind.xaml.cs

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    //数据绑定    (MyLabel是label的name,DataContext绑定的数据为MyData()类
    MyLabel.DataContext = new MyData()
    {
        Title = "这是一个label"
     };
}

 控件

1. 内容控件

(1) Label 

表示控件的文本标签,并提供访问密钥支持。

Label使用绑定来设置目标

<TextBox Name="tb" Width="50"/>
<Label Target="{Binding ElementName=tb}">_File</Label>

(2)TextBlock

TextBlock提供一个轻型控件,用于显示少量流内容。

<!--
    1.TextBlock 设置的text内容 如果标签⾥⾯有⽂本内容 会将其加到text内容后⾯
    2.如果想进⾏换⾏操作 可以在Textblock双标签⾥⾯ 加上LineBreak标签在之后的内容就会换⾏
-->
<TextBlock Text="我是个TextBlock33" FontSize="30" FontWeight="Light" Foreground="Red">
    我是⽂本⼀<LineBreak/>
    我是⽂本⼆<LineBreak/>
    我是⽂本三
</TextBlock>

(3)Button

表示 Windows 按钮控件,该按钮对Click事件做出反应。

(4)Border

在另一个元素四周绘制边框和/或背景。

Border 只能有一个子级。 若要显示多个子元素,需要在父 Border内放置一个附加Panel元素。 然后,可以在该 Panel 元素中放置子元素。

如果要在内容周围显示边框,必须将元素放在父 Border 元素中。

<!--
    BorderThickness边框宽度默认为0 直接设置⼀个参数 代表的是四周宽度
    BorderThickness 有四个参数时 分别代表左边 上边 右边 下边
    我们设置边框颜⾊加上边框宽度 才能准确显示边框的效果
    如果我们需要设置⻆的弧度 需要使⽤CornerRadius属性
-->
    <Border Width="200" Height="80" Background="LightBlue"BorderBrush="Red" BorderThickness="1,1,2,1" CornerRadius="15">
        <Button Background="Transparent" FontSize="20" Foreground="White" Content="我是个按钮" 
                Click="Button_Click" BorderBrush="Transparent">
        </Button>    
    </Border>

(5)RadioButton

表示可由用户选择但不能清除的按钮。 可以通过单击来设置 IsChecked 的 RadioButton 属性,但只能以编程方式清除该属性。

创建两个单独的 RadioButton 组: colorgrp 和 numgrp。 用户可以在每个组中选择一个 RadioButton 。

<StackPanel>
    <RadioButton GroupName="colorgrp">Red</RadioButton>
    <RadioButton GroupName="colorgrp">Blue</RadioButton>
    <RadioButton GroupName="numgrp">1</RadioButton>
    <RadioButton GroupName="numgrp">2</RadioButton>
</StackPanel>

(6)CheckBox

 表示用户可以选择和清除的控件。

 CheckBox 控件继承 ToggleButton 并可以有三种状态:选中 (选定的) 、未选中 (清除) 和不确定。

xaml
<Grid Name="course">
        <CheckBox Name="c"  Content="C语言" Height="50 " Width="80"  HorizontalAlignment="Left" VerticalAlignment="Top" Margin="300,80"  FontSize="18" Background="LightBlue" IsChecked="True"/>
        <CheckBox Name="s" Content="数据结构" Height="50 " Width="100" HorizontalAlignment="Left"   VerticalAlignment="Top" Margin="300,120"  FontSize="18" Background="LightBlue" />
        <CheckBox Name="w" Content="计算机网络" Height="50 " Width="145"  HorizontalAlignment="Left"  VerticalAlignment="Top" Margin="300,160,0,0"  FontSize="18" Background="LightBlue" />
        <CheckBox Name="z" Content="计算机组成原理" Height="50 " Width="160"  HorizontalAlignment="Left"  VerticalAlignment="Top" Margin="300,200,0,0"  FontSize="18" Background="LightBlue" />

        <Button Margin="340,294,380,100" Click="Button_Click">提交</Button>
        <Button Margin="340,350,380,33" Click="Button_Click_1">获取</Button>
    </Grid>
cs
private void Button_Click(object sender, RoutedEventArgs e)
        {
            UIElementCollection childrens = course.Children;
            StringBuilder stringBuilder = new StringBuilder();
            foreach(UIElement iElement in childrens)
            {
                if(iElement is CheckBox && (iElement as CheckBox).IsChecked.Value)
                {
                    stringBuilder.Append((iElement as CheckBox).Content+",");
                }               
            }
            MessageBox.Show("课程为:" + stringBuilder.ToString());
        }

        //只能选择一个,,用于单选按钮的数据绑定
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            StringBuilder builder = new StringBuilder();
            if (c.IsChecked.Value)
            {
                builder.Append(c.Content +",");
            }
            else if(s.IsChecked.Value)
            {
                builder.Append(s.Content + ",");
            }
            else if (w.IsChecked.Value)
            {
                builder.Append(w.Content + ",");

            }
            else if(z.IsChecked.Value)
            {
                builder.Append(z.Content + ",");
            }
            MessageBox.Show("选课为:" + builder.ToString());
        }

 (7)ToolTip

表示一个控件,该控件可创建一个弹出窗口,以便在界面中显示元素的信息。

tooltip是其它控件的属性

<TextBox HorizontalAlignment="Left">TextBox with ToolTip
  <TextBox.ToolTip>
    <TextBlock>Useful information goes here.</TextBlock>
  </TextBox.ToolTip>
</TextBox>

 若用使用ToolTip标签要在控件的ToolTip属性里书写

<TextBox HorizontalAlignment="Left">ToolTip with non-text content
  <TextBox.ToolTip>
    <ToolTip>
        <TextBlock>Useful information goes here.</TextBlock>
    </ToolTip>
  </TextBox.ToolTip>
</TextBox>

 (8)GroupBox

控件用于创建具有用户界面 (UI) 内容边框和标题的容器。

Header属性的使用、GroupBox的内容可以自由组合、

使用自定义模板 ===>>在<Window.Resources>里面使用<ControlTemplate>需要指定key,需要指定作用目标。

<Window x:Class="Wang.Wpf.Control.WindowGroupBox"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Wang.Wpf.Control"
        mc:Ignorable="d"
        Title="WindowGroupBox" Height="450" Width="800">
    <Window.Resources>
        <ControlTemplate x:Key="myGroupBox" TargetType="GroupBox">
            <Grid>
                <Grid.RowDefinitions> <!--分行-->
                    <RowDefinition Height="40"></RowDefinition>
                    <RowDefinition Height="*"></RowDefinition>
                </Grid.RowDefinitions>

                <Border Grid.Row="0" Background="CornflowerBlue"><!--设置第1行的边框-->
                    <Label Foreground="Red" FontSize="20">这是标题</Label>
                </Border>
                
                <Border Grid.Row="1" Background="Aquamarine"><!--设置第2行的边框-->
                    <StackPanel>
                        <TabControl Name="myTabControl" TabStripPlacement="Top" Margin="0, 0, 0, 10" Height="350">
                            <TabItem Name="PersonalInfo">
                                <TabItem.Header>_Personal Info</TabItem.Header>
                                <StackPanel>
                                    <TextBlock>Select your name</TextBlock>
                                    <ListBox Name="empName" >
                                        <ListBoxItem IsSelected="true">Esther</ListBoxItem>
                                        <ListBoxItem>George</ListBoxItem>
                                        <ListBoxItem>Alan</ListBoxItem>
                                        <ListBoxItem>Eric</ListBoxItem>
                                    </ListBox>
                                </StackPanel>
                            </TabItem>
                        </TabControl>
                    </StackPanel>
                </Border>
            </Grid>

        </ControlTemplate>
    </Window.Resources>
    <Grid>
        <GroupBox Template="{StaticResource myGroupBox}">
        </GroupBox>  
    </Grid>
</Window>
<GroupBox Width="300" Height="410">
  <GroupBox.Header> <!--标题-->
    <Label>Employee Data</Label>
  </GroupBox.Header>
    <Grid> <!--内容-->
        <Label>label</Label>
    </Grid>
</GroupBox>

 (9)Expander

表示一种控件,该控件显示具有可折叠内容显示窗口的标题。

   

<!--
    1.如果内容需要跟Expander宽⾼保持⼀致 我们需要设置⽔平和垂直⽅向的排列需要设置为⾮拉伸的状态
        VerticalAlignment="Top" 水平方向靠上(默认为“Stretch”)HorizontalAlignment="Center"水平方向居中
    2.若要使控件Expander正常⼯作,ExpandDirection表示折叠的方向(默认为Down)。
        ExpandDirection设置为Down或Up时,我们不能设置它的⾼度。
        ExpandDirection设置为Left或Right时,我们不能设置它的宽度。
-->
<Grid>
    <Expander Header="折叠框" FontSize="18" Foreground="Blue" IsExpanded="True" BorderThickness="1" 
              BorderBrush="Green" ExpandDirection="Down" VerticalAlignment="Top" HorizontalAlignment="Center" Height="100">
        <StackPanel Orientation="Vertical">
            <CheckBox FontSize="18">C#</CheckBox>
            <CheckBox FontSize="18">JAVA</CheckBox>
            <CheckBox FontSize="18">C++</CheckBox>
        </StackPanel>
    </Expander>
</Grid>

(10) Frame

框架是一种支持导航的内容控件。

A、基本格式(frame的name和绑定的资源source)

 <Frame Name="myFrame" Source="https://www.bilibili.com/" ></Frame>

B、跳转后frame中的页面改变

WindowFrame.xaml

    <Grid>
        <Button Content="点击跳转" Click="Button_Click" HorizontalAlignment="Left" Margin="153,10,0,0" VerticalAlignment="Top" Height="21" Width="69" ></Button>
        <!--NavigationUIVisibility="Visible" 向前后退的导航是否可见-->
        <Frame Name="myFrame" Source="https://www.bilibili.com/" VerticalAlignment="Top" 
               HorizontalAlignment="Center" Width="700" Height="320" Margin="0,50" NavigationUIVisibility="Visible" LoadCompleted="myFrame_LoadCompleted">
        </Frame>
    </Grid>

WindowFrame.xaml.cs

 private void Button_Click(object sender, RoutedEventArgs e)
        {
            
             //1.使用Source绑定跳转的页面 UriKind表示绑定资源的相对路径或者绝对路径
             myFrame.Source = new Uri("https://www.baidu.com",UriKind.Absolute);
             //2.使用Navigate跳转
             MyPages myPages = new MyPages();
             myFrame.Navigate(myPages);
             //使用url
             myFrame.Navigate(new Uri("https://www.baidu.com"));        
        }

带参数传递

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //使用Navigate跳转   
            //使用url带参数
            MyPages myPages = new MyPages();
            myFrame.Navigate(myPages,"参数parameter"); //通过事件加载完成获取到
            //向MyPages这个页面传递参数
            MyPages myPages = new MyPages("这是带参数传到页面上");
            myFrame.Navigate(myPages); 
        }
        private void myFrame_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            object extraData = e.ExtraData;//获取传过来的参数
            Console.WriteLine(extraData); //参数parameter
        }

MyPages.axml

    <Grid Background="Red">
        <Label FontSize="40"  Foreground="White" VerticalAlignment="Center" HorizontalAlignment="Center">
            这是一个页面
        </Label>
    </Grid>

MyPages.axml.cs

   public partial class MyPages : Page
    {
        public MyPages()
        {
            InitializeComponent();
        }
        private string _param; //接受传入的参数
        public MyPages(string _param) :this()
        {
            this._param = _param;
            Console.WriteLine(this._param);
        }
    }