WPF开发笔记:布局

五、布局

1.StackPanel WrapPanel DockPanel
StackPanel



    
    
    

WrapPanel

子元素按顺序排列,如果水平方向:从左到右,超出部分,自动换行到下一行

 

    
        

        
        
            
        
    

//动态添加按钮到 WrapPanel
private void Window_Loaded(object sender, RoutedEventArgs e)
{
    for(int i=1;i<=20;i++)
    {
        Button btn = new Button();
        btn.Content = "btn" + i.ToString("00") + "号";
        btn.Background = new SolidColorBrush(Colors.Transparent);
        btn.Name = "btn" + i;
        btn.Margin = new Thickness(10, 5, 0, 0);
        wpPanel.Children.Add(btn);
    }
    for (int i = 1; i <= 10; i++)
    {
        Button btn = new Button();
        btn.Content = "btn" + i.ToString("00") + "号";
        btn.Background = new SolidColorBrush(Colors.Transparent);
        //btn.Name = "btn" + i;
        btn.Margin = new Thickness(10, 5, 0, 0);
        wpPanel2.Children.Add(btn);
    }
}
DockPanel

停靠面板 顶部, 左边,右边 中间 winform Dock:Top Left Right Buttom

与其他布局控件结合使用

WPF开发笔记:布局_第1张图片



    
    
        
            
        
        
        
        
            
        
        
            
                
                
2.Canvas Grid GroupBox
Canvas

画布面板(坐标面板)定义区域,子元素显示位置,指定相对于面板的坐标,来定位子元素位置。

附加属性:Canvas.left Canvas.Right Canvas.top Canvas.Bottom

坐标:(left,top) (letf,bottom) (right,top) (right,bottom)



    
        
Grid

Grid:网格面板,类似Winform 中TableLayoutPanel 行和列方式布局页面或页面中某一块区域

单元格 一个或多个元素,容器:多个控件stackPanel/WrapPanel/Grid等

指定元素位置: Row Column RowSpan ColumnSpan

Grid 是最复杂一种布局,很强大,很灵活的布局控件

WPF开发笔记:布局_第2张图片


    
    
    
        
        
        
        
    
    
        
        
        
    
    
        
        
        
GroupBox

WPF开发笔记:布局_第3张图片


    
    
        
            
    
    
        
            
                
            
                
        
    

 private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
    //如果没有设置TextBox的name 属性,通过GroupBox控件去获取
    StackPanel spFirst = gbinfo.Content as StackPanel;
    foreach(var ele in spFirst.Children)
    {
        StackPanel sp = ele as StackPanel;
        foreach(var ele2 in sp.Children)
        {
            if(ele2 is TextBox)
            {
                TextBox txt = ele2 as TextBox;
                string name = txt.Text;
            }
        }
    } 
}
3.Expander TabControl Frame
expander

折叠控件 IsExpand 默认隐藏内容

展开事件 Expanded 折叠事件Collapsed


    
    
        
            
            
            
        
    

TabControl

选项卡集合的控件:多个共享相同的空间在屏幕上


   
       
           
               
           
       
       
       
           
               
                   
                   
               
           
    
       
       
           
       
   
   
 /// 
 /// 依次切换
 /// 
 /// 
 /// 
 private void Button_Click_1(object sender, RoutedEventArgs e)
 {
     //tabSystem.SelectedItem = tabSystem.Items[2];
     if (tabSystem.SelectedIndex < tabSystem.Items.Count - 1)
         tabSystem.SelectedIndex += 1;
     else
         tabSystem.SelectedIndex = 0;
 }
Frame

Frame contentControl 支持导航,可以将一个页面导航到另一个页面,可承载Page页。

Tabltem ContentControl 直接在内部添加元素,布局成一个页面,直接将一个页面内嵌到TabItem.

Winform TabControl TabPage 将一个Form 内嵌到TabPage

Wpf中,Window 为根,内部不能是Window


     
     
     
         
             
         
         
             
         
     
 
//1.直接在xaml 代码中设置Source
//2.
//framePage.Source = new Uri("PageRoleInfo.xaml",UriKind.Relative);
//3.先实例化Page对象
PageRoleInfo pageRoleInfo = new PageRoleInfo();
framePage.Navigate(pageRoleInfo);
string ss = "aaa";
framePage.Navigate(pageRoleInfo, ss);   //假设需要传值

六、控件

1.ListView DataGrid Menu
ListView

ListView:用于显示数据项的列表(DataGrid)

DisplayMemberBinding=“{Binding}”


   
      
         
             
                 
                     
                     
                 
                 
                     
                         
                     
                 
             
             
             
             
                 
                     
                         
                 
             
             
             
         
     
    

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    //代码设置Itemssource
    //lvList.ItemsSource = GetUserlist();
    lvList.DataContext = GetUserlist();
}
rivate  List GetUserlist()
{
  
    List list = new List();
    // string sql = "select UserId,UserName,UserState,UserAge from UserInfos";
    // MySqlDataAdapter mySql = new MySqlDataAdapter(sql, myconn);
    list.AddRange(new UserInfo[] {
        new UserInfo(){
        UserId=1,
        UserName="admin",
        UserState=0,
        UserAge=13
        },
        new UserInfo(){
        UserId=2,
        UserName="admin1",
        UserState=1,
        UserAge=31
        },
        new UserInfo(){
        UserId=3,
        UserName="admin2",
        UserState=1,
        UserAge=45
        },
        new UserInfo(){
        UserId=4,
        UserName="admin3",
        UserState=1,
        UserAge=54
        },
   }) ;
    return list;
}
public class UserInfo
{
    public int UserId { get; set; }
    public string UserName { get; set; }
    public int UserState { get; set; }
    public int UserAge { get; set; }
}
DataGrid

网格控件:可以自定义网格显示的数据控件

自定义的网格:列的形式


    
    
        
            
        
        
            
            
            
                
                    
                        
                    
                
            
            
            
            
            
                
                    
                
                
                    
                
            
            
            
                
                    
                        
                
                
                    
                        
                    
                
            
        
    
private void CalendarDate_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
    if (Mouse.Captured is CalendarItem)
        Mouse.Capture(null);
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    //首先设置ComboBox列的数据源
    //colDept.DisplayMemberPath = "DeptName";
    //colDept.ItemsSource = getDepts();
    //如果没有设置列的Name属性
    // DataGridComboBoxColumn deptcol=  dgList.Columns[3] as DataGridComboBoxColumn;
    // deptcol.ItemsSource = getDepts();
    //dgList.ItemsSource = GetUserlist();


    //初始化DGVModel
    //DGVModel dGVModel = new DGVModel();
    //dGVModel.UserList = GetUserList();
    //dGVModel.DeptList = GetDepts();
    //this.DataContext = dGVModel;

}
public class UserInfoNew
{
    public int UserId { get; set; }
    public string UserName { get; set; }
    public int UserState { get; set; }
    public int UserAge { get; set; }
    public int DeptId { get; set; }
}
public class DeptInfo
{
    public int DeptId { get; set; }
    public string DeptName { get; set; }
}
public class DGVModel
{
    public List UserList { get; set; }
    public List DeptList { get; set; }
}
Menu

menu: windows 菜单控件

常用属性:

IsMainMenu 是否接收主菜单激活通知 true 按 alt或 f10激活,如果为false,不能激活。


    
    
    



    



    
    


    
        
            
                
                
                    
                
            
            
            
            
        
        
        
        
        
    

private void MiRole_click(object sender, ExecutedRoutedEventArgs e)
{
    NewPage newPage = new NewPage();
    newPage.Show();
}

private void MiOpen_click(object sender, ExecutedRoutedEventArgs e)
{
    OpenPage openPage = new OpenPage();
    openPage.Show();
}
  • **动态生成菜单项:**递归加载菜单数据,分层数据模板
  • 获取菜单数据:按层次结构组织的数据列表
  • **菜单模型:**编号 名称 父菜单编号 快捷键
  • **菜单项模型:**编号 名称 快捷键 子菜单列表
  • **数据模板:**分成数据模板 HeaderedItemsControl Menu TreeView

递归加载菜单的方法,分层数据模板嵌入Menu控件中


2.ContextMenu TreeView ToolBar
ContextMenu

(右键菜单) 上下文菜单


    
    

private void lbl_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    ContextMenu.PlacementTarget = lbl;
    ContextMenu.IsOpen = true;
}
TreeView

基本属性

 
    


    
        
            
                
                
            
            
            
            
        
        
            
            
            
            
        
        
    

 /// 
        /// 节点选择响应事件
        /// 
        /// 
        /// 
 private void tvList_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs e)
 {
     var val = e.NewValue as TreeViewItem;
     MessageBox.Show(val.Header.ToString());
 }
 
  

代码创建节点

动态生成节点树–分层数据模板


ToolBar

ToolBar 为一组命令或控件的容器


     



    



    
        
private void ComboBoxItem_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    lbl.Content = "相应事件";
}

private void BtnNew_Click(object sender, RoutedEventArgs e)
{
    Window newWin = new Window();
    newWin.Title = "新建页面";
    Frame frame = new Frame();
    frame.Source= new Uri("PageRoleInfo.xaml", UriKind.Relative);
    newWin.Content = frame;
    newWin.Show();
}
ToolBarTray

ToolBarTray 布局多个ToolBar的容器,呈放多个ToolBar Band 行 BandIndex 带区索引


    
        
            
                
            
        
        
            
                
            
        
        
            
                
            
        
        
            
                
            
        
        
    
    
        
3.StatusBar MediaElement RichTextBox
StatusBar控件

使用 :主页面显示:登录者,登录时间 当前操作的模块名称 版权信息 进程过程

 
    
        
            
                
                    
                        
                        
                        
                        
                    
                
            
        
        
        
            
                
        
        
            
                
        
        
            
                
        
    

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    tbTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}
MediaElement

媒体播放控件:音视频


    
    
        
    

媒体播放器制作

 
    


    
        
            
                
            
            
                
                    
                    
                
            
            
        
   
    
        
        
        
        
    
    
        
private void BtnNew_Click(object sender, RoutedEventArgs e)
{
    Window newWin = new Window();
    newWin.Title = "新建页面";
    Frame frame = new Frame();
    frame.Source= new Uri("PageRoleInfo.xaml", UriKind.Relative);
    newWin.Content = frame;
    newWin.Show();
    
}
System.Timers.Timer timer = null;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
    timer = new System.Timers.Timer();
    timer.Interval = 1000;
    timer.Elapsed += Timer_Elapsed;
   // tbTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}
private void Timer_Elapsed(object sender,System.Timers.ElapsedEventArgs e)
{
    //子线程执行
    this.Dispatcher.Invoke(new Action(() =>
    {
        //主线程
        posSlider.Value = me.Position.TotalSeconds;
        SetTime();
    }));
}
/// 
/// 设置时间文本框的值
/// 
private void SetTime()
{
    lblTime.Content = string.Format( "{0:00}:{1:00}:{2:00}",me.Position.Hours,me.Position.Minutes,me.Position.Seconds);
}

private void openBtn_Click(object sender, RoutedEventArgs e)
{
    OpenFileDialog ofd = new OpenFileDialog();
    ofd.Filter = @"视频文件(*.avi格式)|*.avi|视频文件(*.wav格式)|*.wmv|视频文件(*.wmv格式)|*.mp4|视频文件(*.mp4格式)|*.mp4|All Files|*.*";
    if(ofd.ShowDialog()==false)
    {
        return;
    }
    string filePath = "";
    filePath = ofd.FileName;
    if (filePath == "")
        return;
    //设置媒体源
    me.Source = new Uri(filePath, UriKind.Absolute);
    playBtn.IsEnabled = true;
    me.Play();
    timer.Start();
    playBtn.Content = "暂停";
}

private void playBtn_Click(object sender, RoutedEventArgs e)
{
    SetPlayer(true);
    PlayPause();
   
}
/// 
/// 播放或暂停
/// 
private void PlayPause()
{
    if (playBtn.Content.ToString() == "播放")
    {
        me.Play();
        timer.Start();
        playBtn.Content = "暂停";
        me.ToolTip = "单击暂停";
    }
    else
    {
        me.Pause();
        timer.Stop();
        playBtn.Content = "播放";
        me.ToolTip = "单击播放";
        SetTime();
    }
}
private void SetPlayer(bool bl)
{
    stopBtn.IsEnabled = bl;
    playBtn.IsEnabled = bl;
    backBtn.IsEnabled = bl;
    forwardBtn.IsEnabled = bl;
}

private void stopBtn_Click(object sender, RoutedEventArgs e)
{
    me.Stop();
    posSlider.Value = 0;
    lblTime.Content = "0:0:0";
    playBtn.Content = "播放";
    timer.Stop();
}

private void forwardBtn_Click(object sender, RoutedEventArgs e)
{
    me.Pause();
    timer.Stop();
   me.Position = me.Position + TimeSpan.FromSeconds(10);
    SetTime();
    me.Play();
    timer.Start();
}

private void backBtn_Click(object sender, RoutedEventArgs e)
{
    me.Pause();
    timer.Stop();
    me.Position = me.Position - TimeSpan.FromSeconds(10);
    SetTime();
    me.Play();
    timer.Start();
}

private void me_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    
    PlayPause();
}
/// 
/// 媒体加载完毕后
/// 
/// 
/// 
private void me_MediaOpened(object sender, RoutedEventArgs e)
{
    posSlider.Maximum = me.NaturalDuration.TimeSpan.TotalSeconds;
    lblTime.Content = "0:0:0";

}

private void posSlider_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    me.Pause();
    timer.Stop();
    int val = (int)posSlider.Value;
    me.Position = new TimeSpan(0, 0, 0, val);
    SetTime();
    me.Play();
    timer.Start();
}

private void me_MediaEnded(object sender, RoutedEventArgs e)
{
    me.Stop();
    timer.Stop();
}

RichTextBox

    
    
        
            
                
                百度一下
            
            
                
            
            
   private void Button_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show("这是个按钮");
}

private void Hyperlink_Click(object sender, RoutedEventArgs e)
{
    Process proc = new Process();
    proc.StartInfo.FileName = "http://www.baidu.com";
    proc.Start();
}

private void GetText_Click(object sender, RoutedEventArgs e)
{
    TextRange range=new TextRange(rtbContext.Document.ContentStart, rtbContext.Document.ContentEnd);
    string contentTxt = range.Text;
    MessageBox.Show(contentTxt);
}

悬浮球

 
 
     
        
     
 

日志打印功能

    
        
    
public MainWindow()
{
    InitializeComponent();
    ThreadPool.QueueUserWorkItem(sender =>
    {
        while (true)
        {
            this.txtLog.Dispatcher.BeginInvoke((Action)delegate
            {
                this.txtLog.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff\r\n"));
                if (IsVerticalScrollBarAtBottom)
                {
                    this.txtLog.ScrollToEnd();
                }
            });
            Thread.Sleep(600);
        }
    });

}
public bool IsVerticalScrollBarAtBottom
{
    get
    {
        bool atBottom = false;

        this.txtLog.Dispatcher.Invoke((Action)delegate
        {
            double dVer = this.txtLog.VerticalOffset;       //获取竖直滚动条滚动位置
            double dViewport = this.txtLog.ViewportHeight;  //获取竖直可滚动内容高度
            double dExtent = this.txtLog.ExtentHeight;      //获取可视区域的高度

            if (dVer + dViewport >= dExtent)
            {
                atBottom = true;
            }
            else
            {
                atBottom = false;
            }
        });

        return atBottom;
    }
}

你可能感兴趣的:(学习笔记,wpf,c#,开发语言)