顯示具有 WPF 標籤的文章。 顯示所有文章
顯示具有 WPF 標籤的文章。 顯示所有文章

2018年7月9日 星期一

WindowService與WPF實作捕捉未做TryCatch的Exception方法

Window Service版本使用
using System.Security.Permissions;
using System.IO;

[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)]
    protected override void OnStart(string[] args)
    {   AppDomain currentDomain = AppDomain.CurrentDomain;
        currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
        ...
        Your codes...
        ....
    }
    void MyHandler(object sender, UnhandledExceptionEventArgs args)
    {
        Exception e = (Exception)args.ExceptionObject;
        WriteToFile("Simple Service Error on: {0} " + e.Message + e.StackTrace);
    }
    private void WriteToFile(string text)
    {
        string path = "C:\\ServiceLog.txt";
        using (StreamWriter writer = new StreamWriter(path, true))
        {
            writer.WriteLine(string.Format(text, DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt")));
            writer.Close();
        }
    }


WPF版本使用



private void Application_DispatcherUnhandledException(object sender, 
                       System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
    // Handle the exception
}

2018年4月10日 星期二

C# WPF TextBox Binding List

首先建立一個類別叫ListToTextConverter,程式碼如下。

    public class ListToTextConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            StringBuilder sb = new StringBuilder();
            foreach (string s in (List)value)
            {
                if(sb.Length != 0)
                {
                    sb.Append(",");
                }
                sb.Append(s);
            }

            return sb.ToString();
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string[] lines = ((string)value).Split(new string[] { @"\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            return lines.ToList();
        }
    }


建立完成後,在View頁面上加入該類別,這樣才能引用,程式碼如下。

                
    
        
            
                
            
            
        
    
  
    
  



這樣就算完成引用了,當程式在執行時,在Binding過程當中,會執行到ListToTextConverter類別內執行Convert方法,並且轉換成字串,再給TextBox。

2017年7月27日 星期四

C# WPF Textbox只能輸入數字

在引用的View.Xaml畫面裡面加入這行,做事件綁定。

這樣就可以做到只能輸入數字了。
DelayStartTimeTextBox.PreviewTextInput += StaticResourceModel.PreviewTextInput;
    public static class StaticResourceModel
    {
        public static void PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            e.Handled = new System.Text.RegularExpressions.Regex("[^0-9]+").IsMatch(e.Text);
        }
    }