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

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年9月28日 星期四

C# ObservableCollection 此類型的 CollectionView 不支援從 與發送器執行續不同的執行緒變更其SourceCollection

今天撰寫OPC Server遇到一個問題是 我的OPCServerSource已經跟UI的TreeView綁定了 可是我又透過OPC Client去取得Browser的Server的資料 再要將Server資料匯入到OPCServerSource時,出現如圖下的錯誤。



解決的方法是在要匯入的地方加入Application.Current.Dispatcher.BeginInvoke((Action)delegate () {};這行,就可以解決問題了

private void ServerBrowserItemsUI(List serverList)
{
  Application.Current.Dispatcher.BeginInvoke((Action)delegate ()
  {
    serverList.ToList().ForEach(args =>
    {
    OPCServerSource.Add(new Model.OPCServer() { ProgName = args.progID, ProgID = args.clsid.ToString(), Url = new System.Windows.Media.Imaging.BitmapImage(new Uri(@"/OPCDASettingWPFLib;component/Common/Images/lightIcon_green_20.png", UriKind.RelativeOrAbsolute)) });
    });
  });
}

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);
        }
    }