WPF 常用的方法总结。

有些时候,不能把控件写死在xaml里,需要后台动态加载,这就需要后台设置控件的属性。这是我的一些总结。

1.后台设置颜色方法 :

 stackPanel.Background = new SolidColorBrush(Colors.Red);
stackPanel.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FAE2AE"));

2.后台设置样式方法:

 startLine.Style = FindResource("FloatButtonLine") as Style;

3.后台设置Margin方法:

Thickness lblthickness = new Thickness();
                lblthickness.Top = 10;
                lblthickness.Left = 10;                
                lbl.Margin = lblthickness;

4.获取当前文件路径的七种方法:

//获取模块的完整路径。
string path1 = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
//获取和设置当前目录(该进程从中启动的目录)的完全限定目录
string path2 = System.Environment.CurrentDirectory;
//获取应用程序的当前工作目录
string path3 = System.IO.Directory.GetCurrentDirectory();
//获取程序的基目录
string path4 = System.AppDomain.CurrentDomain.BaseDirectory;
//获取和设置包括该应用程序的目录的名称
string path5 = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
//获取启动了应用程序的可执行文件的路径
string path6 = System.Windows.Forms.Application.StartupPath;
//获取启动了应用程序的可执行文件的路径及文件名
string path7 = System.Windows.Forms.Application.ExecutablePath;

StringBuilder str=new StringBuilder();
str.AppendLine("System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName:" + path1);
str.AppendLine("System.Environment.CurrentDirectory:" + path2);
str.AppendLine("System.IO.Directory.GetCurrentDirectory():" + path3);
str.AppendLine("System.AppDomain.CurrentDomain.BaseDirectory:" + path4);
str.AppendLine("System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase:" + path5);
str.AppendLine("System.Windows.Forms.Application.StartupPath:" + path6);
str.AppendLine("System.Windows.Forms.Application.ExecutablePath:" + path7);
string allPath = str.ToString();

5 限制TextBox输入正整数,在textBox中事件PreviewTextInput完成输入字符串限制。

        private void tbTest_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            Regex re = new Regex("[^0-9.-]+");
            e.Handled = re.IsMatch(e.Text);
        }

6.打开文件:

	 OpenFileDialog openFileDialog = new OpenFileDialog();
     openFileDialog.Title = "选择数据源文件";
     openFileDialog.Filter = "txt文件|*.txt";
     openFileDialog.FileName = string.Empty;
     openFileDialog.FilterIndex = 1;
     openFileDialog.Multiselect = false;
     openFileDialog.RestoreDirectory = true;
     openFileDialog.DefaultExt = "txt";
     if (openFileDialog.ShowDialog() == false)
     {
         return;
     }
    string  txtFile = openFileDialog.FileName;

7.打开文件夹

	System.Windows.Forms.FolderBrowserDialog folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();
    folderBrowserDialog.Description = "选择Word文档生成的文件夹";
    folderBrowserDialog.ShowNewFolderButton = false;
    folderBrowserDialog.RootFolder = Environment.SpecialFolder.Personal;
    folderBrowserDialog.ShowDialog();
    if (folderBrowserDialog.SelectedPath == string.Empty) 
    {
        return;
    }
    string wordFolder = folderBrowserDialog.SelectedPath;

8.打开图片字符串名称转换格式为byte

        /// <summary>
        /// 打开图片文件并转成byte
        /// </summary>
        /// <param name="fileName"></param>
        private byte[] OpenReadFile(string fileName)
        {
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fs);
            byte[] imageData = new byte[br.BaseStream.Length];
            int nRet = int.Parse(br.BaseStream.Length.ToString());
            imageData = br.ReadBytes(nRet);
            fs.Close();
            return imageData;
        }

9.byte[] 转bitmap

 private System.Drawing.Bitmap BytesToBitmap(byte[] Bytes)
        {
            MemoryStream stream = null;
            try
            {
                stream = new MemoryStream(Bytes);
                return new System.Drawing.Bitmap((System.Drawing.Image)new System.Drawing.Bitmap(stream));
            }
            catch (ArgumentNullException ex)
            {
                throw ex;
            }
            catch (ArgumentException ex)
            {
                throw ex;
            }
            finally
            {
                stream.Close();
            }
        }

10.遍历文件夹下的文件方法:

 DirectoryInfo dir = new DirectoryInfo(Common.path);
 FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();

11.读取文件名转换为byte

byte[] data = File.ReadAllBytes(dlg.FileName);

12.读取xml文件方法:

1.加头文件:
 using System.Xml;
2.定义一个读取类型
    public class threshold 
    {
        public float value;
        public string name;
    }

public static bool FolderExists()
{
    if (!System.IO.File.Exists(configName))
    {
        return false;
    }
    return true;
}

public static List<threshold> LoadConfigThreshold()
{
    List<threshold> thresholdList = new List<threshold>();
    XmlDocument document = new XmlDocument();
    document.Load(configName);
    XmlNode xn = document.SelectSingleNode("config");
    XmlNodeList xnl = xn.ChildNodes;
    foreach (XmlNode xlChild in xnl)
    {
        threshold threshold = new threshold();
        XmlElement xe = (XmlElement)xlChild;
        float value;
        float.TryParse(xe.GetAttribute("value"),out value);
        threshold.value = value;
        threshold.name = xe.GetAttribute("name");
        thresholdList.Add(threshold);
    }
    return thresholdList;
}

13. 保留2位小数14.WPF 后端设置样式方法:

//设置样式
Style myStyle = (Style)this.FindResource("TabItemStyle");
//TabItemStyle 这个样式是引用的资源文件中的样式名称

14 字符串转enum类型

public enum RectType { Roll, Flat, Palm, Dmg, Photo, Slap, PalmSide, Barcode };

public RectType Type;

Type = (RectType)Enum.Parse(typeof(RectType),type);

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
WPF(Windows Presentation Foundation)是一种用于开发Windows应用程序的UI框架,它提供了一种以XAML(Extensible Application Markup Language)为基础的方式来构建用户界面。 在WPF中,我们可以通过自定义控件来满足特定的需求。通过方法传值是一种常见的方式,可以实现自定义控件的重要功能。 首先,我们需要定义一个自定义控件。可以通过继承现有的控件类,例如`Button`或`TextBox`,也可以直接继承自`Control`类。在自定义控件的代码中,我们可以定义自己的依赖属性,这些属性可以通过方法进行传值。 在自定义控件的代码中,可以定义一个公共方法,用于接收参数并进行处理。例如,定义一个名为`SetValue`的方法,用于设置控件的值。方法的参数可以是任何类型,根据实际需求进行定义。 在方法中,我们可以修改自定义控件的状态或属性值,以达到相应的效果。例如,在`SetValue`方法中,可以修改自定义控件的显示文本或颜色等属性。 在使用自定义控件时,可以通过调用定义的方法,传递相应的值。例如,通过调用自定义控件的`SetValue`方法,将需要的值传递给控件。 总结起来,通过方法传值是一种在WPF中实现自定义控件的常见方式。在自定义控件的代码中,我们可以定义方法来接收参数,并根据需求进行处理。通过调用这些方法,可以将需要的值传递给自定义控件,实现相应的功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

楚楚3107

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值