WPF开发笔记:控件

WPF 控件

一、控件分类

  • 布局控件: Panel
  • **内存控件 :**ContentControl 只能容纳一个控件或布局控件
  • 带标题内容控件: 内容控件剋设置标题 Header 父类:HeaderedContentControl
  • 条目控件: 可以显示一列数据,数据类型一般相同 ItemControl
  • 带标题的条目控件: 条目控件可以设置标题Header 父类:HeaderedItemControl
  • 特殊内容控件: 常用的控件:TextBox PasswordBox TextBlock Image等。

二、WPF应用程序组成

  • app.config :配置未见连接字符串 配置信息
  • app.xaml :设置应用程序起始文件,系统级资源
  • app.xaml.cs:app.xaml 文件的后台类文件
  • MainWindow.xaml:Window—WPF应用程序界面与xaml设计文件
  • MainWindow.xaml.cs:xaml窗口文件后台代码文件
  • **<Application.Resources>:**定义整个WPF应用程序相关资源

三、Windows 介绍

<Window x:Class="Pwnguo.WPFNETS.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"Title="MainWindow"                 Height="450" Width="800"
        ShowInTaskbar="False"                  <!-- 窗口是否具有任务栏按钮  -->
        WindowStartupLocation="CenterScreen"   <!-- 窗口首次西安市出现的位置 -->
        WindowState="Normal"                   <!-- 指定窗口状态,最大化,最小化,或默认-->
        Topmost="True"                         <!-- 窗口置顶-->
        Icon="imgs/thresh.jpg" Loaded="Window_Loaded"<!-- 窗口加载事件-->>
<!-- 
其他常见窗口事件设置
closing 
MouseDoubleClick
MouseLeftButtonDown
MouseLeftButtonUp
MouseRightButtonDown
MouseRigthButtonUp
-->

控件介绍

1、Button ReadioButton CheckBox
<!--------------------------+    Button    +-------------------------------->

<Button Name="btn_Login" Content="Login" Foreground="Beige" BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" IsCancel="True" IsDefault="True">
    <Button.Background>
        <ImageBrush ImageSource="imgs/contours.jpg"></ImageBrush>
    </Button.Background>
</Button>

<!-------------------------+  ReadioButton +-------------------------------->

<RadioButton Content="admin" GroupName="authority" HorizontalAlignment="Left" VerticalAlignment="Top" IsChecked="True" Checked="RadioButton_Checked"/>
            <RadioButton Content="User" GroupName="authority" HorizontalAlignment="Left" VerticalAlignment="Top" Checked="RadioButton_Checked"/>
            <RadioButton Content="visitor" GroupName="authority" HorizontalAlignment="Left" VerticalAlignment="Top" Checked="RadioButton_Checked"/>
<!-- RadioButton 相应事件
private void RadioButton_Checked(object sender, RoutedEventArgs e)
{
    MessageBox.Show((sender as RadioButton).Content.ToString() );
}
-->  

<!-- RadioButton 动态加载 添加到<stackpanel 子项>
<StackPanel x:Name="stackPanel">           
   <RadioButton Content="admin" GroupName="authority" HorizontalAlignment="Left" 				VerticalAlignment="Top" IsChecked="True" Checked="RadioButton_Checked"/>
   <RadioButton Content="User" GroupName="authority" HorizontalAlignment="Left" 			 	 VerticalAlignment="Top" Checked="RadioButton_Checked"/>
   <RadioButton Content="visitor" GroupName="authority" HorizontalAlignment="Left"       		VerticalAlignment="Top" Checked="RadioButton_Checked"/>
</StackPanel>

c# 代码 Window窗口加载时动态加载
 private void Window_Loaded(object sender, RoutedEventArgs e)
{
    RadioButton radioButton = new RadioButton();
    radioButton.Content = "Guest";
    radioButton.GroupName = "authority";
    radioButton.HorizontalAlignment = HorizontalAlignment.Left;
    radioButton.VerticalAlignment = VerticalAlignment.Top;

    stackPanel.Children.Add(radioButton);
}
 -->

<!-------------------------+    CheckBox   +-------------------------------->
<!--静态添加Checkbox-->
 <CheckBox Name="chkOPEX" 
                  Content="运维" IsChecked="True" IsThreeState="True"
                  HorizontalAlignment="Left" Margin="47,53,0,-53" />
        <CheckBox  Content="开发" IsChecked="True" IsThreeState="True"
                  HorizontalAlignment="Right" Margin="0,53,73,-53"/>
        <CheckBox  Content="运营" IsChecked="True" IsThreeState="True"
                  HorizontalAlignment="Left" Margin="146,53,0,-53" />
        <Button Content="OK" HorizontalAlignment="Left" VerticalAlignment="Top" 
                Click="Button_Click" Margin="159,129,0,0" Height="25" Width="72"/>
<!--动态添加ChekcBox-->
<Button Content="Add" HorizontalAlignment="Left" VerticalAlignment="Top" 
                Click="Button_Click" Margin="112,129,0,0" Height="25" Width="72"/>
<Button x:Name="BtnGet" Content="Get" HorizontalAlignment="Left" VerticalAlignment="Top" 
               Click="BtnGet_Click" Margin="219,129,0,0" Height="25" Width="72"/>
<!--C#代码-->
        private void Button_Click(object sender, RoutedEventArgs e)
        {
           
            //代码CheckBox
        string[] names = { "运维", "安全", "运营", "售前", "售后" };
        for(int i = 0; i < names.Length; i++)
            {
                CheckBox checkBox = new CheckBox();
                checkBox.Content = names[i];
                checkBox.HorizontalAlignment = HorizontalAlignment.Left;
                checkBox.VerticalAlignment = VerticalAlignment.Top;
                checkBox.Margin = new Thickness(40+i*80,60,0,0);
                gridChk.Children.Add(checkBox);
            }
        }
        private void BtnGet_Click(object sender, RoutedEventArgs e)
        {
            string strContens = "";
            foreach (UIElement element in gridChk.Children)
            {
                if (element is CheckBox)
                {
                    CheckBox check = element as CheckBox;
                    if (check.IsChecked == true)
                    {
                        if (strContens != "")
                            strContens += ",";
                        strContens += check.Content.ToString();
                    }
                }
            }
            MessageBox.Show(strContens);
        }
    }
2、Image Border ComboBox
image

image控件显示

<!--Stretch 默认 uniform  StretchDirection 默认Both-->
<Image x:Name="imgSource" HorizontalAlignment="Left" VerticalAlignment="Top" Height="250"
          Stretch="Fill" StretchDirection="Both"  Width="350" Source="imgs/geometric.jpg"/>
        <Button Content="GetImage" HorizontalAlignment="Left" VerticalAlignment="Top" Click="Button_Click_1" Margin="329,358,0,0"/>

代码指定Image

//方式一
//相对路径  UriKind.Relative指定相对路径参数
//Source ImageSource
imgSource.Source = new BitmapImage(new Uri("imgs/grabcut.jpg", UriKind.Relative));
//方式二/三
//WPF 支持两种授权 application:/// 和 siiteoforigin:///..
//Pack URI 方案 pack://授权/路径
//授权 指定包含部件的程序包的类型,而路径则指定部件在程序包中的位置
//siteoforigin 图片--》属性 --》生成操作—》内容 application--》属性--》生成操作--》资源/内容
imgSource.Source = new BitmapImage(new Uri("pack://application:,,,/imgs/gradient.jpg", UriKind.Absolute));
//方式四
//图片--》属性--》  (复制到输出目录--》始终复制  /生成操作—》内容 )
imgSource.Source = new BitmapImage(new Uri(AppDomain.CurrentDomain.BaseDirectory + "imgs/colorspace.jpg", UriKind.Absolute));
Border

borderBrush 边框颜色 BorderThickness 粗细 CornerRadius 圆角的弧度 background border 内部背景色

应用:布局面板一起使用 作为任意控件的边框提示(不是一个布局面板)

Border 只能有一个元素作为他的子元素

要显示多个元素?利用布局面板(子元素)

<Grid Name="WindowGrid">
<Border BorderBrush="Khaki" BorderThickness="1" CornerRadius="10" Background="Aquamarine" HorizontalAlignment="Left" VerticalAlignment="Top" Height="267" Width="600" Margin="149,81,0,0">
     <Grid Name="BorderGrid" HorizontalAlignment="Center" VerticalAlignment="Top" Width="462" Height="200" Background="Azure">
            <Grid.ColumnDefinitions>
                <ColumnDefinition/>
                <ColumnDefinition/>
                <ColumnDefinition/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <Button Grid.Column="0" Grid.ColumnSpan="2" Margin="0,0,100,28">ok</Button>               <Button Grid.Column="1" Margin="0,0,0,28">ok1</Button>
            <Button Grid.Column="2" Margin="0,0,0,28">ok2</Button>
            <Button Grid.Column="2" Grid.ColumnSpan="2" Margin="115,0,0,28">ok3</Button>
      </Grid>
  </Border>
</Grid>

在这里插入图片描述

ComboBox

下拉框绑定数据 手动添加

 <!--IsDropDownOpen="True" ComboBox收缩展开状态-->
<ComboBox HorizontalAlignment="Left" VerticalAlignment="Top" Width="200" Height="30" 
                  VerticalContentAlignment="Center">
   <ComboBoxItem Content="请选择" IsSelected="True"  ></ComboBoxItem>
   <ComboBoxItem Content="开发部" ></ComboBoxItem>
   <ComboBoxItem Content="运维部" ></ComboBoxItem>
   <ComboBoxItem Content="运营部" ></ComboBoxItem>
   <ComboBoxItem Content="销售部" ></ComboBoxItem>
</ComboBox>

绑定数据:

//Mainwondow.xaml.cs
public partial class MainWindow : Window
    {
        MainViewModel mainViewModel = null;
        public MainWindow()
        {
            InitializeComponent();
            mainViewModel = new MainViewModel();
            this.DataContext = mainViewModel;
        }
        /// <summary>
        /// ComData:ComboBox Name="ComData"
        /// ComboxData:class( ComboxData.cs)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //获取数据源
            List<ComboboxData> cboxdatas = GetcboxDatas();
            ComData.SelectedValuePath = "ComboboxID";  //项目的值对应的属性名
            ComData.DisplayMemberPath = "ComboboxName"; //项目的文本对应的属性名
           
            
//1.代码里ItermSource : IEnumerable(List)
             ComData.ItemsSource = cboxdatas;  指定数据源
            /不能直接移除,也不能添加
            //如果仍然要添加或移除其中的项  移除先设置ItemSource =NUll 移除list列表数据重新指定                    ItemSource
             ComData.ItemsSource = null;
            cboxdatas.Add(new ComboboxData()
            {
                ComboboxID = 4,
                ComboboxName= "安全部"
            }) ;
            ComData.ItemsSource = cboxdatas;
//2. DataContext=List  ItemSource="{Binding}"
              ComData.DataContext = cboxdatas;                     
                
  
            
//3.Items.Add 
            //动态添加删除 利用操作list列表数据达到增加删除
            ComData.Items.Add(new ComboboxData()
            {
                ComboboxID = 4,
                ComboboxName = "安全部"
            });
            foreach (ComboboxData cData in cboxdatas)
            {
                ComData.Items.Add(cData);
            }

        }
      
            
      //数据源
      private List<ComboboxData> GetcboxDatas()
      {
            List <ComboboxData> cboxData = new List<ComboboxData>();
            cboxData.AddRange(new ComboboxData[] {
                new ComboboxData(){
                ComboboxID=0,
                ComboboxName="请选择"
                },
                 new ComboboxData(){
                ComboboxID=1,
                ComboboxName="开发部"
                },
                  new ComboboxData(){
                ComboboxID=2,
                ComboboxName="运维部"
                },
                   new ComboboxData(){
                ComboboxID=3,
                ComboboxName="销售部"
                }
            }) ;
            return cboxData;
        }
        private void btnRemove_Click(object sender, RoutedEventArgs e)
        {
            //动态删除
            int index = ComData.SelectedIndex;
            ComData.Items.RemoveAt(index);
        }
    }
}
//combobox class
public class ComboboxData
{
    private int _ComboboxID;
    private string _ComboboxName;

    public string ComboboxName
    {
        get { return _ComboboxName; }
        set { _ComboboxName = value; }
    }

    public int ComboboxID
    {
        get { return _ComboboxID; }
        set { _ComboboxID = value; }
    }
}
3、ListBox DatePicker Calender
ListBox

手动添加项

<ListBox x:Name="listBoxName" HorizontalAlignment="Left" Height="230" Width="260"        `				  					              SelectionChanged="listBoxName_SelectionChanged" VerticalAlignment="Top" >
  <ListBoxItem Content="安全部" IsSelected="True"></ListBoxItem>
  <ListBoxItem Content="信息部"></ListBoxItem>
  <ListBoxItem Content="运营部"></ListBoxItem>
  <ListBoxItem Content="销售部"></ListBoxItem>
</ListBox>

绑定数据源

两个ListBox 中项互相移动不太适合指定ItemsSource,Items.Add方式添加项可以灵活的舔加和移除

        <!-- SelectionMode="Multiple" list 多选-->
        <ListBox x:Name="listBoxData" HorizontalAlignment="Left" Height="230" Width="260" 
                 SelectionChanged="listBoxName_SelectionChanged"          
            VerticalAlignment="Top" ItemsSource="{Binding}"  SelectionMode="Multiple">
        </ListBox>
 public partial class MainWindow : Window
 {
     MainViewModel mainViewModel = null;
     public MainWindow()
     {
         InitializeComponent();
         mainViewModel = new MainViewModel();
         this.DataContext = mainViewModel;
     }
     /// <summary>
     /// ComData:ComboBox Name="ComData"
     /// ComboxData:class( ComboxData.cs)
     /// </summary>
     /// <param name="sender"></param>
     /// <param name="e"></param>

//绑定数据还用 ComboBox 数据
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
 //方式一 ItemsSource
            //listBoxData.ItemsSource = GetDatas();
 //方式二 DataContext    <ListBox ItemsSource="{Binding}"></ListBox>    
            listBoxData.DataContext= GetDatas();
            
                  
            listBoxData.SelectedValuePath = "ComboboxID";
            listBoxData.DisplayMemberPath = "ComboboxName";
            listBoxData.SelectedIndex = 1;
        }
        private List<ComboboxData> GetDatas()
        {
            List <ComboboxData> cboxData = new List<ComboboxData>();
            cboxData.AddRange(new ComboboxData[] {
                 new ComboboxData(){
                ComboboxID=1,
                ComboboxName="开发部"
                },
                  new ComboboxData(){
                ComboboxID=2,
                ComboboxName="运维部"
                },
                   new ComboboxData(){
                ComboboxID=3,
                ComboboxName="销售部"
                }
            }) ;
            return cboxData;
        }
      

        private void listBoxName_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //选择项类型 由绑定或添加时数据的类型决定
            //MessageBox.Show(listBoxData.SelectedItem.ToString());
            ComboboxData seectItem = listBoxData.SelectedItem as ComboboxData;
        }
 }
DatePicker
  <!--IsTodayHighlighted 默认True IsDropDownOpen 默认false FirstDayOfWeek Sunday
       DisplayDate 要显示的时间 并不显示在日期中SelectedDateFormat 默认为short -->
<DatePicker HorizontalAlignment="Left" Margin="103,133,0,0" VerticalAlignment="Top"
            Height="53" Width="321"
   DisplayDate="2022-01-01" DisplayDateStart="2022-01-01" DisplayDateEnd="2022-12-31"
            FirstDayOfWeek="Monday" IsDropDownOpen="False" IsTodayHighlighted="False"
            SelectedDate="2022-01-12" SelectedDateFormat="Long">
   
    <DatePicker.Resources>
        <Style TargetType="DatePickerTextBox">
            <Setter Property="BorderThickness" Value="0"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate>
                        <TextBox x:Name="PART_TextBox" Text="{Binding Path=SelectedDate,
                            StringFormat={}{0:yyyy-MM-dd},RelativeSource={RelativeSource
                            AncestorType={x:Type DatePicker}}}"/>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </DatePicker.Resources>
</DatePicker>
Calender

Calender 可视化月历控件 月历显示选择日期

<Calendar x:Name="CalendarDate" HorizontalAlignment="Left" Margin="56,42,0,0" VerticalAlignment="Top" Height="232" Width="420"
                 DisplayMode="Month" DisplayDateStart="2022-1-1" DisplayDateEnd="2022-12-31"
                IsTodayHighlighted="True"  SelectionMode="MultipleRange"
                SelectedDatesChanged="Calendar_SelectedDatesChanged"
                 PreviewMouseUp="CalendarDate_PreviewMouseUp" 
              >

        </Calendar>
        <TextBox x:Name="DateStart" HorizontalAlignment="Left" Margin="162,279,0,0" Text="" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
        <TextBox x:Name="DateEnd" HorizontalAlignment="Left" Margin="314,279,0,0" Text="" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
        <TextBox x:Name="DateSel" HorizontalAlignment="Left" Margin="461,279,0,0" Text="TextBox" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
        <Button Content="Button" HorizontalAlignment="Left" Margin="637,293,0,0" VerticalAlignment="Top" Click="Button_Click"/>

代码获取当前选择日期

 private void Calendar_SelectedDatesChanged(object sender, SelectionChangedEventArgs e)
{
    DateStart.Text = CalendarDate.SelectedDates.First().ToShortDateString();
    DateEnd.Text = CalendarDate.SelectedDates.Last().ToShortDateString();

}

private void Button_Click(object sender, RoutedEventArgs e)
{
    DateSel.Text = CalendarDate.SelectedDate.Value.ToString();
}
//解决Calendar button Captured 冲突
private void CalendarDate_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
    if (Mouse.Captured is CalendarItem)
        Mouse.Capture(null);
}
4、Slider ProgressBar
progessBar
    <Grid>
        <!--Orientation-->
        <ProgressBar Name="pbar1" HorizontalAlignment="Left" Height="92"  VerticalAlignment="Top" Width="33" Maximum="100" Minimum="0" Value="30"
                     Orientation="Vertical" Margin="50,90,0,0" />
        <ProgressBar Name="pbar2" HorizontalAlignment="Left" Height="26" Margin="290,200,0,0" VerticalAlignment="Top" Width="236" Value="0" 
                     Maximum="100" Minimum="0" Orientation="Horizontal" RenderTransformOrigin="0.5,0.5" IsIndeterminate="False" ValueChanged="pbar2_ValueChanged"/>
        <Button Content="加载" HorizontalAlignment="Left" Margin="306,262,0,0" VerticalAlignment="Top" Click="Button_Click"/>
        <Label Name="labVal" Content=" " HorizontalAlignment="Left" Margin="408,248,0,0" VerticalAlignment="Top"/>

    </Grid>
 private void Button_Click(object sender, RoutedEventArgs e)
{
    double max = pbar2.Maximum;
    Task.Run(() =>
    {
        for(int i = 0; i < max; i++)
        {
            pbar2.Dispatcher.Invoke(() =>
            {
                pbar2.Value = i;
                labVal.Content = pbar2.Value + "%";
            });     
            Thread.Sleep(100);
        }
    });
}

private void pbar2_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
    labVal.Content = pbar2.Value + "%";
}
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值