WPF知识点【6-11章节】

上面的代码中, 定义了一个DataTemplate , 顶一个 长宽10px的border用于显示颜色代码, 绑定到Border背景颜色上, 定义了一个TextBlock用于展示颜色的代码。
下面为后台的绑定代码

List<Color> ColorList = new List<Color>();
            ColorList.Add(new Color() { Code = "#FF8C00" });
            ColorList.Add(new Color() { Code = "#FF7F50" });
            ColorList.Add(new Color() { Code = "#FF6EB4" });
            ColorList.Add(new Color() { Code = "#FF4500" });
            ColorList.Add(new Color() { Code = "#FF3030" });
            ColorList.Add(new Color() { Code = "#CD5B45" });

            cob.ItemsSource = ColorList;
            lib.ItemsSource = ColorList;

最终的测试效果如下所示:

img

ItemsControl模板

定义ItemsControl 主要分两个步骤: 1.设置ItemsPanel容器, 用于容纳列表的最外层容器 2.定义子项的DataTemplate

<ItemsControl Name="ic">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel Orientation="Horizontal"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>

            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Button Width="50" Height="50" Content="{Binding Code}"/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

上面代码中, 定义了一个WarpPanel 容器为ItemControl的 最外层容器, 子项数据模板则绑定了一个按钮, 后台代码绑定几条数据, 查看其效果: 横排排列五个按钮, 内容分别是 1~6.

 List<Test> tests = new List<Test>();
            tests.Add(new Test() { Code = "1" });
            tests.Add(new Test() { Code = "2" });
            tests.Add(new Test() { Code = "3" });
            tests.Add(new Test() { Code = "4" });
            tests.Add(new Test() { Code = "6" });
            ic.ItemsSource = tests;

最终的测试效果如下所示:

img

查看ItemsControl可视化树的结构组成?

img

剖析该结构, 可以看到, 紫色的1处, 为最外层的WrapPanel容器, 用于容纳排列按钮, 由于该示例设置了 Orientation="Horizontal" , 所以按钮则按水平排列, 再看 橘色 2处, 可以看见子项外层由一个内容呈现包括着, 内容为一个按钮, 由于绑定搞得数据是5个, 所以分别生成了内容为1~6的5个按钮。

  • 说明: 那是不是以为则ItemsPanel 放置任何元素都行? 很明显是不行的。 ItemsPanel的容器需要满足一个条件, 则是属于Panel族的元素, 否则会提示以下错误:

    img

关于每种元素的分类可以看关于控件介绍的文章: https://www.cnblogs.com/zh7791/p/11372473.html

ContentTemplate模板

WPF控件模板(6) - 痕迹g - 博客园 (cnblogs.com)

Wpf之Bingding

WPF中的binding(九)- 使用Binding的RelativeSource_Hyman的博客-CSDN博客

WPF绑定案例

WPF 的内部世界{Binding /}的用法

{Binding}指自身的DataContext {Binding .}指自身对象 {Binding list/id} 指数据源中的List中的属性

image-20210827171235436

XAML界面代码结构与说明

六、带检索功能的Combobox

自定义控件

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace DH.Share.Comm.Base
{
    public class EditComboBox : ComboBox
    {
        private bool t = true;//首次获取焦点标志位
        private ObservableCollection<object> bindingList = new ObservableCollection<object>();//数据源绑定List
        private string editText = "";//编辑文本内容

        /// <summary>
        /// 注册依赖事件
        /// </summary>
        public static readonly DependencyProperty ItemsSourcePropertyNew = DependencyProperty.Register("MyItemsSource", typeof(IEnumerable), typeof(EditComboBox), new FrameworkPropertyMetadata(new PropertyChangedCallback(ValueChanged)));
        /// <summary>
        /// 数据源改变,添加数据源到绑定数据源
        /// </summary>
        /// <param name="d"></param>
        /// <param name="e"></param>
        private static void ValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            EditComboBox ecb = d as EditComboBox;
            ecb.bindingList.Clear();
            //遍历循环操作
            foreach (var item in ecb.MyItemsSource)
            {
                ecb.bindingList.Add(item);
            }
        }
        /// <summary>
        /// 设置或获取ComboBox的数据源
        /// </summary>
        public IEnumerable MyItemsSource
        {
            get
            {
                return (IEnumerable)GetValue(ItemsSourcePropertyNew);
            }
    
            set
            {
                if (value == null)
                    ClearValue(ItemsSourcePropertyNew);
                else
                    SetValue(ItemsSourcePropertyNew, value);
            }
        }
        /// <summary>
        /// 重写初始化
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInitialized(EventArgs e)
        {
            base.OnInitialized(e);
            this.IsEditable = true;
            this.IsTextSearchEnabled = false;
            this.ItemsSource = bindingList;
        }
        /// <summary>
        /// 下拉框获取焦点,首次搜索文本编辑框
        /// </summary>
        /// <param name="e"></param>
        protected override void OnGotFocus(RoutedEventArgs e)
        {
            if (t)
                FindTextBox(this);
            else
                t = false;
        }
        /// <summary>
        /// 搜索编辑文本框,添加文本改变事件
        /// </summary>
        /// <param name="obj"></param>
        private void FindTextBox(DependencyObject obj)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child is TextBox)
                {
                    //注册文本改变事件
                    (child as TextBox).TextChanged += EditComboBox_TextChanged;
                }
                else
                {
                    FindTextBox(child);
                }
            }
        }
        /// <summary>
        /// 文本改变,动态控制下拉条数据源
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void EditComboBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox tb = sender as TextBox;
            if (tb.IsFocused)
            {
                this.IsDropDownOpen = true;
                if (editText == this.Text)
                    return;
                editText = this.Text;
                SetList(editText);
            }
        }
        /// <summary>
        /// 组合框关闭,数据源恢复
        /// </summary>
        /// <param name="e"></param>
        protected override void OnDropDownClosed(EventArgs e)
        {
            base.OnDropDownClosed(e);
            if (MyItemsSource == null)
                return;
            foreach (var item in MyItemsSource)
            {
                if (!bindingList.Contains(item))
                    bindingList.Add(item);
            }
        }
        /// <summary>
        /// 过滤符合条件的数据项,添加到数据源项中
        /// </summary>
        /// <param name="txt"></param>
        private void SetList(string txt)
        {
            try
            {
                string temp1 = "";
                string temp2 = "";
                if (MyItemsSource == null)
                    return;
                foreach (var item in MyItemsSource)
                {
                    temp1 = item.GetType().GetProperty(this.DisplayMemberPath).GetValue(item, null).ToString();
                    if (string.IsNullOrEmpty(this.SelectedValuePath))
                    {
                        temp2 = "";
                    }
                    else
                    {
                        temp2 = item.GetType().GetProperty(this.SelectedValuePath).GetValue(item, null).ToString();
                    }
                    if (temp1.Contains(txt) || temp2.StartsWith(txt))
                    {
                        if (!bindingList.Contains(item))
                            bindingList.Add(item);
                    }
                    else if (bindingList.Contains(item))
                    {
                        bindingList.Remove(item);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }

}

xaml使用方法

xmlns:ec="clr-namespace:DH.Share.Comm.Base;assembly=DH.Share.Comm"

<StackPanel Orientation="Horizontal">
                            <TextBlock Margin="20 0 0 0" Text="{Binding Sd.Sname}" Width="300" Height="40" Background="Red"/>
                            <ec:EditComboBox 
                                             Width="200"
                                             Height="30"
                                             Padding="2"
                                             VerticalContentAlignment="Center"
                                             DisplayMemberPath="Snumber"
                                             FontSize="15"
                                             MyItemsSource="{Binding DataList, Mode=TwoWay}"
                                             SelectedItem="{Binding Sd, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                                             SelectedValuePath="Snumber" />

</StackPanel>

List数据源

Model

using System;
using System.Collections.Generic;
using System.Text;

namespace DH.Share.Comm.DataHelp.Entity
{
   public class ServiceEntity
    {
        private string _snumber;

        public string Snumber
        {
            get { return _snumber; }
            set { _snumber = value; }
        }
      

        private string _sname;

        public string Sname
        {
            get { return _sname; }
            set { _sname = value; }
        }
   }
}

ViewModel

List<ServiceEntity> DataList = new List<ServiceEntity>() 
{ new serviceEntity { Snumber = "1001", Sname = "郭主任" },
	new serviceEntity {	Snumber	= "1002",	Sname	=	"张经理" } } ;


				private ServiceEntity sd;

        public ServiceEntity Sd
        {
            get { return sd; }
            set { sd = value;
                RaisePropertyChanged();
            }
        }

C# ComboBox的联动操作(三层架构)

七、prism

区域管理

//AppStaticInfo.RegionManager.AddToRegion("WorkRegion", AppStaticInfo.Container.Resolve());
//AppStaticInfo.Container.RegisterForNavigation();

//AppStaticInfo.Container.RegisterForNavigation(SysRegView可以是变量,"SysRegView");

//AppStaticInfo.RegionManager.RegisterViewWithRegion(RegionNames.WorkRegion, "SysRegView",type类型SysRegView可以是变量);
//var _view = AppStaticInfo.Container.Resolve();
//IRegion region = AppStaticInfo.RegionManager.Regions[RegionNames.WorkRegion];
//region.Add(_view, "SysReg");
//region.Activate(region.GetView("SysReg"));

找不到region用下面两行代码

DefaultSet defaultSet = AppStaticInfo.Container.Resolve();

RegionManager.SetRegionManager(defaultSet,AppStaticInfo.RegionManager);

​ AppStaticInfo.RegionManager.RegisterViewWithRegion(RegionNames.SysSetRegion,typeof(SysRegView));

查找region中的view并删除

//if (AppStaticInfo.region != null)
//{
// var rviews = AppStaticInfo.region.Views;
// foreach (var view in rviews)
// {
// AppStaticInfo.region.Remove(view);
// }
// AppStaticInfo.region = null;
//}
//AppStaticInfo.region = AppStaticInfo.RegionManager.Regions[RegionNames.UserRegion];

根据字符串删除view对象

public DelegateCommand CloseCommand
{
get => new DelegateCommand(() =>
{
// 关闭操作
// 根据URI获取对应的已注册对象名称
var obj = _unityContainer.Registrations.FirstOrDefault(v => v.Name == NavUri);
string name = obj.MappedToType.Name;
// 根据对象名称再从Region的Views里面找到对象
if (!string.IsNullOrEmpty(name))
{
var region = _regionManager.Regions["MainContentRegion"];
var view = region.Views.FirstOrDefault(v => v.GetType().Name == name);
// 把这个对象从Region的Views里移除
if (view != null)
region.Remove(view);
}
});
}

导航

//AppStaticInfo.RegionManager.RequestNavigate(RegionNames.UserRegion, "UserListView");
//AppStaticInfo.RegionManager.AddToRegion(RegionNames.UserRegion, AppStaticInfo.Container.Resolve());

去除window边框和背景

WindowStyle="None" Background="Transparent"
AllowsTransparency="True"
WindowChrome.WindowChrome="{DynamicResource WindowChromeKey}">
<Window.Resources>

<WindowChrome.ResizeBorderThickness>
0
</WindowChrome.ResizeBorderThickness>

</Window.Resources>

事件绑定命令方法

xmlns:i="http://schemas.microsoft.com/xaml/behaviors"

文本连接Command

Reset Role

注册弹出窗口

AppStaticInfo.Container.RegisterDialog<DialogView, DialogViewModel>();

封装弹窗方法

public void DialogShow(string Title,string Info,Action action)
{

DialogParameters param = new();
param.Add("Title",Title);
param.Add("Info",Info);
AppStaticInfo.DialogService.ShowDialog("DialogView", param, arg =>
{
if (arg.Result == ButtonResult.OK)
action();
});

DialogView.xaml


prism:Dialog.WindowStyle

    <Style TargetType="Window">
        <Setter Property="Width" Value="400" />
        <Setter Property="Height" Value="260" />
        <Setter Property="WindowChrome.WindowChrome">
            <Setter.Value>
                <WindowChrome GlassFrameThickness="-1" />
            </Setter.Value>
        </Setter>
    </Style>

​ </prism:Dialog.WindowStyle>

​ <Grid.RowDefinitions>



​ </Grid.RowDefinitions>

​ <TextBlock Grid.Row="1"
​ Margin="30"
​ Text="{Binding DialogMsg}" />
​ <StackPanel Grid.Row="2"
​ HorizontalAlignment="Right"
​ Orientation="Horizontal">
​ <Button Margin="0,20"
​ Command="{Binding OkCommand}"
​ Content="确定" />
​ <Button Margin="30,20"
​ Command="{Binding CancleCommand}"
​ Content="取消" />


using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Prism.Mvvm;
using Prism.Commands;

namespace DH.Share.Controls.UserControls
{
///


/// DialogView.xaml 的交互逻辑
///

public partial class DialogView : UserControl
{
public DialogView()
{
InitializeComponent();
}
}
public class DialogViewModel : BindableBase,IDialogAware
{

    private string title;
    
    public string Title
    {
        get { return title; }
        set { title = value;RaisePropertyChanged(); }
    }
    private string dialogMsg;
    
    public string DialogMsg
    {
        get { return dialogMsg; }
        set { dialogMsg = value; RaisePropertyChanged(); }
    }
    public DelegateCommand OkCommand
    {
        get => new(() =>
        {
            RequestClose?.Invoke(new DialogResult(ButtonResult.OK));
        });
    }
    public DelegateCommand CancleCommand
    {
        get => new(() =>
        {
            RequestClose?.Invoke(new DialogResult(ButtonResult.No));
        });
    }
    
    public event Action<IDialogResult> RequestClose;
    
    public bool CanCloseDialog()
    {
        return true;
    }
    
    public void OnDialogClosed()
    {
       
    }
    
    public void OnDialogOpened(IDialogParameters parameters)
    {
        title = parameters.GetValue<string>("Title");
        dialogMsg = parameters.GetValue<string>("Info");
    }
}

}

命令调用弹出窗口

public DelegateCommand CloseCommand { get => new DelegateCommand(() =>
{
AppStaticInfo.DialogShow("提示消息", "确定要关闭信息窗口吗?", () => { CommandBase.CloseView("BusinessMsgView", RegionNames.TabItemRegion); });

      });
    }

ListView内容双击bing命令

xaml内容

<ListView.ItemContainerStyle>

</ListView.ItemContainerStyle>

xaml.cs内容

private void OnListViewItemDoubleClick(object sender, MouseButtonEventArgs e)
{
var vm = this.DataContext as BusinessInfoViewModel;
vm.OpenCommand.Execute();//OpenCommand是viewmodel中的命令
}

八、EFcore

数据库映射为Models

Scaffold-DbContext "server=127.0.0.1;database=MyBBSDb;uid=sa;pwd=123456" "Microsoft.EntityFrameworkCore.SqlServer" -o Models

Scaffold-DbContext "server=39.99.242.232;database=DHSWXX;uid=sa;pwd=YQrzxkj1" "Microsoft.EntityFrameworkCore.SqlServer" -o Models -force

Models映射为数据库

Add-Migration InitialCreate-v0.1
Add-Migration InitialCreate-v0.1 -Context SysDbContext
Remove-Migration (撤回)
Update-Database 
Update-Database  -Context SysDbContext

判断对象的属性值是否为空

public bool CheckIsNull(this object o, string[] fields)
{
if (o != null)
{
for (int i = 0; i < fields.Length-1; i++)
{

            var v = o.GetType().GetProperty(fields[i]);
                if (string.IsNullOrEmpty(v.GetValue(o).ToString())) 
                {
                    return false;
                }
                ;
            }
            return true;
            
        }
        else
        {
            return false;
        }

    }

九、字体图标

xaml 中text=""等同于c#中text="\ue641"

Regex.Unescape(str)从数据库中取出\ue641转换为字体图标格式,自动转换转义字符\ \u为\u

string unicodes = "e72a";
       string newStr = System.Text.RegularExpressions.Regex.Unescape(string.Format("\\u{0}", unicodes ));

十、vs快捷键

1、格式化代码:Ctrl+E,D
2、格式化部分代码:选中代码->Ctrl+K,F。或者Ctrl+E,F。

3、折叠cs文件所有方法:Ctrl+M,O

4、打开或折叠所有代码:Ctrl+M,L  (打开或折叠当前代码段:Ctrl+M,M)

5、新建文件:Alt+Shift+C

6、交换上下行:Shift+Alt+T

7、任务型注释:// TODO:注释部分  
8、打开任务注释:Ctrl+W,T


9、在ASP.NET页面切换(HTML): Ctrl+PgUp/Ctrl+PgDn

10、在windows窗体切换:F7/Shift+F7 (代码/设计)

11、跳转到指定行号Ctrl+G


12、快速查找:光标停留在需要查找的词上面,使用快捷键Ctrl+F3可以跳转到下一个相同的词。按Shift+F3可以往上查找。


13、查找和替换:
当你想查找/替换掉某个字符串的时候,你可以按快捷键“Ctrl+F”或者“Ctrl+H”,进行这一操作。另外VS支持正则表达式和通配符。

如果你想从整个项目进行查找/替换,你需要使用快捷键“Ctrl+Shift+F”或者“Ctrl+Shift+H”。当然这一切都可以在菜单栏找到。“编辑->查找和替换”。当你想中止全局替换的时候,你可以使用快捷键“Ctrl+Pause Break”。

14、书签:
书签是很有用的功能,用过Chrome的都知道。在VS当中,书签同样适用。它可以帮你保存位置,以便你写代码。

放置书签:Ctrl+B,T。

上一个书签:Ctrl+B,P。

下一个书签:Ctrl+B,N。

删除所有书签:Ctrl+K,C。(居然打错了,对不起,谢谢@河蟹社会 提醒),正确的是Ctrl+B,C。

除此之外,VS还提供了其它的书签操作。

15、跳转到定义: F12。

16、行编辑(复制,剪切,删除,交换)

当你在光标停留行使用快捷键Ctrl+C,X,L时,可以复制,剪切,删除整行内容。当然,右键也是可以的。跟平时的复制,剪切,删除就是选中和没选中代码的区别而已。

如果你想交换上下两行,你可以使用快捷键(Shift+Alt+T),前提是光标要停留在上面那一行。替换之后,光标会一直跟随原本的那一行。

17、生成方法存根 Ctrl+K,M . 比如 先写好方法名称(当前并没有方法实现) 按快捷键 vs会自动生成一个当前方法名的结构。

18、将光标跳转到对应括号 Ctrl+]  可以试试 Ctrl+Shift+] 哟

image-20230509112611875

注释比较规范,是如何实现的呢?首先要知道,当你建立一个VS文件时,事实上是调用了对应的模版文件,我们以vs2017为例,来说一下添加自定义注释的方法

模块文件位置

接口模版:C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\ItemTemplates\CSharp\Code\2052\Interface

类模版 :C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\ItemTemplates\CSharp\Code\2052\Class

模块文件信息

using System;
using System.Collections.Generic;
$if$ ($targetframeworkversion$ >= 3.5)using System.Linq;
$endif$using System.Text;
$if$ ($targetframeworkversion$ >= 4.5)using System.Threading.Tasks;
$endif$
namespace $rootnamespace$
{
    /// <summary>
    /// 功能描述    :$safeitemrootname$  
    /// 创 建 者    :$username$
    /// 创建日期    :$time$ 
    /// 最后修改者  :$username$
    /// 最后修改日期:$time$ 
    /// </summary>
    class $safeitemrootname$
    {
    }
}

其中有一些条件的预判断,如果运行时的版本来引用不同的命名空间,如果我们有自己的模块类库,也可以在这里引进来,$safeitemrootname是类的文件名称,$user是当前登陆用户名,$time是当前日期时间。

十一、博客园

dotnet tool install -g dotnet-cnblog  安装上传工具
dotnet-cnblog  配置id,用户,密码
dotnet-cnblog proc -f 文件名.md
posted @   元祖  阅读(102)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示