C#编程之Slider控件使用

今天说一下slider控件的使用。该控件主要使用功能有以下几点:

  1. slider值的获取;
  2. slider值的设定;
  3. slider值的变化量;
  4. slider值的范围;

下面一一讲解:

slider值的获取,可以直接将其绑定对编辑框或文本框  Text="{Binding ElementName=mySlider,Path=Value}" 或者 double k = mySlider.Value; 

slider值设定可以直接赋值给Value: mySlider.Value = 1500; 

slider变化量由tick设定: TickFrequency="5" (代表每次变化量为5),因为slider值类型是double类型,所以如果需要忽略小数点时,可以通过: IsSnapToTickEnabled="True" 实现.

slider值范围设定:通过selection设置: SelectionStart="1000" SelectionEnd="2000" 

例程:通过设定slider参数,将slider值通过串口发射出去(考虑到slider变化频率过高,导致发射失败,这里采用定时器读取slider值,如果发现其值改变,则发送数据,类似于加入消抖功能):

  1. 设计UI界面:
  2. 后台代码:
     1 <Window x:Class="ServoApp.MainWindow"
     2         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     3         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     4         Title="ServoApp Milo lu 1.0v" Height="250" Width="390" Background="LightBlue" ResizeMode="CanMinimize">
     5     <Grid x:Name="SeroApp">
     6         <Label Name="m_Com" Content="COM" Margin="10,10,0,0" Width="50" VerticalAlignment="Top" HorizontalAlignment="Left" />
     7         <ComboBox Name="myCOM"      Margin="85,10,0,0" Width="80" VerticalAlignment="Top" HorizontalAlignment="Left" Background="LightBlue"/>
     8         <Label Name="m_Baud" Content="BRT" Margin="10,50,0,0" Width="50" VerticalAlignment="Top" HorizontalAlignment="Left"/>
     9         <ComboBox Name="myBaudRate" Margin="85,50,0,0" Width="80" VerticalAlignment="Top" HorizontalAlignment="Left" Background="LightBlue"/>
    10         <Label Name="m_range" Content="Range:" Margin="10,85" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="Bold"/>
    11         <TextBlock Name="tblock" Text="{Binding ElementName=mySlider,Path=Value}" Margin="85,85" VerticalAlignment="Top" HorizontalAlignment="Left"/>
    12         <Slider Name="mySlider" Margin="20,130,0,0" Width="300" VerticalAlignment="Top" HorizontalAlignment="Left" 
    13                 IsSnapToTickEnabled="True" Value="1500" Minimum="1000" Maximum="2000" 
    14                 SelectionStart="1000" SelectionEnd="2000" TickFrequency="5" TickPlacement="BottomRight"/>
    15         <Button Name="myBtn" Content="Open"  Margin="10,180,0,0" Width="50"  VerticalAlignment="Top" HorizontalAlignment="Left" Click="open_Clk"/>
    16         <Label Content="Rx" Margin="200,10,0,0" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="Bold"/>
    17         <TextBox Name="myRX" Margin="200,50,0,0" Width="150" Height="20" VerticalAlignment="Top" HorizontalAlignment="Left" Background="LightBlue"/>
    18     </Grid>
    19 </Window>
    XALM
  3. 添加源码:
      1 using System;
      2 using System.Collections.Generic;
      3 using System.Linq;
      4 using System.Text;
      5 using System.Threading.Tasks;
      6 using System.Windows;
      7 using System.Windows.Controls;
      8 using System.Windows.Data;
      9 using System.Windows.Documents;
     10 using System.Windows.Input;
     11 using System.Windows.Media;
     12 using System.Windows.Media.Imaging;
     13 using System.Windows.Navigation;
     14 using System.Windows.Shapes;
     15 using System.IO.Ports;//supported serial port
     16 using System.Security.Cryptography;//supported security crypto
     17 using System.Threading;
     18 using System.Windows.Threading;
     19 
     20 namespace ServoApp
     21 {
     22     /// <summary>
     23     /// Interaction logic for MainWindow.xaml
     24     /// </summary>
     25     public partial class MainWindow : Window
     26     {
     27         System.Timers.Timer myTimer = new System.Timers.Timer(50);
     28         SerialPort myPort = new SerialPort();
     29         bool myPortCurrentStateOpen;
     30         string str_tmp;
     31         public MainWindow()
     32         {
     33             InitializeComponent();
     34             //comboxs init
     35             myComboxs();
     36             //receive routine
     37             myPort.DataReceived += DataReceived;
     38             myTimer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
     39             myTimer.Enabled = true;
     40         }
     41         private void DataReceived(object sender,SerialDataReceivedEventArgs e)
     42         {
     43             byte[] inbuf = new byte[4];
     44             try 
     45             {
     46                 myPort.Read(inbuf, 0, inbuf.Length);
     47                 string str = System.Text.Encoding.Default.GetString(inbuf);
     48                 this.Dispatcher.Invoke(new Action(() =>
     49                 {
     50                     myRX.Text = str;
     51                     }));
     52             }
     53             catch(Exception ex)
     54             {
     55                 MessageBox.Show(ex.Message);
     56             }
     57         }
     58         private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
     59         {
     60             try 
     61             {
     62                 this.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
     63                     {
     64                         if (myPortCurrentStateOpen == true)
     65                         {
     66                             if (mySlider.IsEnabled == false)
     67                             {
     68                                 myRX.IsReadOnly = true;
     69                                 myRX.IsEnabled = true;
     70                                 mySlider.IsEnabled = true;
     71                             }
     72                             if (str_tmp != tblock.Text)
     73                             {
     74                                 str_tmp = tblock.Text;
     75                                 myPort.Write(str_tmp);
     76                             }
     77                         }
     78                         else
     79                         {
     80                             myRX.IsEnabled = false;
     81                             mySlider.IsEnabled = false;
     82                         }
     83                     }));
     84             }
     85             catch (Exception ex)
     86             {
     87                 MessageBox.Show(ex.Message);
     88             }
     89         }
     90         private void myComboxs()
     91         {
     92             //Set COM items
     93             myCOM.Items.Add("COM0");
     94             myCOM.Items.Add("COM1");
     95             myCOM.Items.Add("COM2");
     96             myCOM.Items.Add("COM3");
     97             myCOM.Items.Add("COM4");
     98             //default value
     99             myCOM.SelectedIndex = myCOM.Items.IndexOf("COM1");
    100             //Set BRT items
    101             myBaudRate.Items.Add("2400");
    102             myBaudRate.Items.Add("4800");
    103             myBaudRate.Items.Add("9600");
    104             myBaudRate.Items.Add("38400");
    105             myBaudRate.Items.Add("115200");
    106             //default value
    107             myBaudRate.SelectedIndex = myBaudRate.Items.IndexOf("9600");
    108             myPortCurrentStateOpen = false;
    109         }
    110 
    111         private void open_Clk(object sender, RoutedEventArgs e)
    112         {
    113             try
    114             {
    115                 if (myPortCurrentStateOpen == false)
    116                 {
    117                     if(myPort.IsOpen)
    118                     {
    119                         myPort.Close();
    120                     }
    121                     myPort.BaudRate = int.Parse(myBaudRate.Text);
    122                     myPort.DataBits = 8;
    123                     myPort.PortName = myCOM.Text;
    124                     myPort.Open();
    125                     myPortCurrentStateOpen = true;
    126                     myBtn.Content = "Close";
    127                 }
    128                 else
    129                 {
    130                     myPort.Close();
    131                     myBtn.Content = "Open";
    132                     mySlider.Value = 1500;
    133                     myPortCurrentStateOpen = false;
    134                 }
    135             }
    136             catch(Exception ex)
    137             {
    138                 MessageBox.Show(ex.Message);
    139             }
    140         }
    141     }
    142 }
    CS
  4. 运行:
  5. End,谢谢!
原文地址:https://www.cnblogs.com/lumao1122-Milolu/p/12606092.html