Xaml文件
<UserControl x:Class="CMSystemSetModule.UserControls.AutoLayoutControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<UserControl.Resources>
<Style x:Key="textBoxStyle" TargetType="{x:Type TextBox}" BasedOn="{StaticResource CommonTextBoxStyle}">
<Setter Property="HorizontalAlignment" Value="Left"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="Height" Value="32"/>
<Setter Property="Width" Value="182"/>
</Style>
<Style x:Key="ParamKeyLabelStyle" TargetType="{x:Type Label}" BasedOn="{StaticResource CommonLabelStyle}">
<Setter Property="FontSize" Value="14"/>
</Style>
<Style x:Key="ParamKeyTBStyle" TargetType="{x:Type TextBlock}" BasedOn="{StaticResource CommonTextBlockStyle}">
<Setter Property="FontSize" Value="14"/>
</Style>
</UserControl.Resources>
<Grid x:Name="gridAutoLayout" Visibility="Visible">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{DynamicResource sysSettintPageDescWidth}"></ColumnDefinition>
<ColumnDefinition Width="10"></ColumnDefinition>
<ColumnDefinition Width="182*"></ColumnDefinition>
</Grid.ColumnDefinitions>
</Grid>
</UserControl>
Cs文件
using CMSystemSetModule.Model.CameraConfig;
using CMSystemSetModule.Model.Common;
using CMSystemSetModule.ResourcesManger;
using CMSystemSetModule.Utils;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace CMSystemSetModule.UserControls
{
/// <summary>
/// AutoLayoutControl.xaml 的交互逻辑
/// </summary>
public partial class AutoLayoutControl : UserControl
{
#region 全局变量
private string cameraNo;
private string cameraName;
//用于工业相机算法界面的全部相机
private string allCameraNo;
private JToken originalJToken;
private JToken currentJToken;
private Func<string> GetConfigFunc;
private Func<string, string> GetCameraConfigFunc;
private Func<string, string> SetConfigFunc;
private Action ReloadAutoLayoutPage;
//存图页面父类标签需要加粗
private bool isSaveImage;
//部分参数中英文转换字典
private Dictionary<string, string> enzhDic = new Dictionary<string, string>();
//输入框原来的值,用于最小值复原
private Dictionary<string, string> textBoxOldValueDic = new Dictionary<string, string>();
public bool IsContentChanaged
{
get
{
//考虑到下发失败的情况,因此currentJToken需要获取底层模块的数据再比较,以底层数据为准
currentJToken = this.GetCurrentJToken();
if (currentJToken == null || originalJToken == null)
{
return false;
}
return !(this.originalJToken.ToString() == this.currentJToken.ToString());
}
}
#endregion
#region 构造函数
private AutoLayoutControl(Func<string, string> SetConfigFunc)
{
InitializeComponent();
this.SetConfigFunc = SetConfigFunc;
}
public AutoLayoutControl(Func<string> GetConfigFunc, Func<string, string> SetConfigFunc, Action ReloadAutoLayoutPage, bool isSaveImage)
:this(SetConfigFunc)
{
this.GetConfigFunc = GetConfigFunc;
this.ReloadAutoLayoutPage = ReloadAutoLayoutPage;
this.isSaveImage = isSaveImage;
//originalJToken = this.GetJToken();
//ReloadControls();
}
public AutoLayoutControl(Func<string, string> GetCameraConfigFunc, Func<string, string> SetConfigFunc, string cameraNo, string cameraName)
: this(SetConfigFunc)
{
this.GetCameraConfigFunc = GetCameraConfigFunc;
this.cameraNo = cameraNo;
this.cameraName = cameraName;
originalJToken = this.GetCameraJToken(this.cameraNo);
ReloadControls();
}
/// <summary>
/// 只有工业相机算法页面会调用,因为涉及到全部相机这种类型
/// </summary>
/// <param name="GetCameraConfigFunc"></param>
/// <param name="SetConfigFunc"></param>
/// <param name="cameraNo"></param>
/// <param name="allCameraNo"></param>
public AutoLayoutControl(Func<string, string> GetCameraConfigFunc, Func<string, string> SetConfigFunc, string cameraNo, string cameraName, string allCameraNo)
: this(SetConfigFunc)
{
this.GetCameraConfigFunc = GetCameraConfigFunc;
this.cameraNo = cameraNo;
this.allCameraNo = allCameraNo;
originalJToken = this.GetCameraJToken(this.cameraNo);
ReloadControls();
}
#endregion
#region 方法
public bool Save()
{
currentJToken = this.GetCurrentJToken();
//原始数据刷新到当前数据即可
this.originalJToken = this.currentJToken == null ? null : this.currentJToken.DeepClone();
return true;
}
public void Back()
{
if (this.originalJToken != null && this.currentJToken != null)
{
//没有修改过不需要回滚
if (this.originalJToken.ToString() != this.currentJToken.ToString())
{
this.currentJToken = this.originalJToken.DeepClone();
string strCurrentJObject = JsonConvert.SerializeObject(currentJToken);
this.SetConfig(strCurrentJObject);
}
}
}
public void InitOriginalJToken()
{
originalJToken = this.GetJToken();
}
private JToken GetCurrentJToken()
{
if (GetConfigFunc != null)
{
currentJToken = this.GetJToken();
}
else if (GetCameraConfigFunc != null)
{
currentJToken = this.GetCameraJToken(this.cameraNo);
}
return currentJToken;
}
private JToken GetJToken()
{
if (GetConfigFunc != null)
{
string strConfig = GetConfigFunc();
JObject jObject = (JObject)JsonConvert.DeserializeObject(strConfig);
if (jObject == null)
{
return null;
}
if (jObject["result"] != null && jObject["result"].First != null)
{
return jObject["result"].First as JToken;
}
}
return null;
}
private JToken GetCameraJToken(string cameraNo)
{
try
{
if (GetCameraConfigFunc != null)
{
CameraSerialModel model = new CameraSerialModel();
model.cameraSerial = cameraNo;
string strConfig = GetCameraConfigFunc(JsonConvert.SerializeObject(model));
JObject jObject = (JObject)JsonConvert.DeserializeObject(strConfig);
if (jObject == null)
{
return null;
}
if (jObject["result"] != null && jObject["result"].First != null)
{
return jObject["result"].First as JToken;
}
}
}
catch (Exception ex)
{
Logger.GetInstance().log.Error(ex.ToString());
}
return null;
}
public void ReloadControls()
{
try
{
//新建控件花了0.08秒(16个控件)
gridAutoLayout.Children.RemoveRange(0, gridAutoLayout.Children.Count);
gridAutoLayout.RowDefinitions.Clear();
if (GetConfigFunc != null)
{
currentJToken = this.GetJToken();
this.CreateControls(currentJToken);
}
else if (GetCameraConfigFunc != null)
{
currentJToken = this.GetCameraJToken(this.cameraNo);
this.CreateControls(currentJToken);
}
}
catch (Exception ex)
{
Logger.GetInstance().log.Error(ex.ToString());
}
}
private void CreateControls(JToken jToken)
{
try
{
if (jToken != null)
{
JEnumerable<JToken> jTokens = jToken.Children().First().Children();
int rowIndex = 0;
//加粗存图模块父类节点
bool isBold = true;
foreach (JToken item in jTokens)
{
string typeValue = this.GetJPropertyValue(item, ConstModel.typeKey);
RowDefinition row = new RowDefinition();
int rowheight = ConstModel.rowHeight;
if (typeValue == ConstModel.checkboxType)
{
rowheight = 96;
}
row.Height = new GridLength(rowheight);
gridAutoLayout.RowDefinitions.Add(row);
if ((item as JProperty) != null)
{
string controlTag = (item as JProperty).Name;
if (typeValue == ConstModel.checkboxButtonType)
{
CreateCameraNameLabel(gridAutoLayout, rowIndex);
}
else
{
//这里名称要从字段转换为中文标签,在资源文件中对应
CreateLabel(gridAutoLayout, controlTag, rowIndex, isBold);
}
isBold = false;
switch (typeValue)
{
case ConstModel.enumType:
CreateComboBox(gridAutoLayout, controlTag, item, rowIndex);
break;
case ConstModel.boolType:
CreateCheckbox(gridAutoLayout, controlTag, this.GetJPropertyValue(item, ConstModel.valueKey), rowIndex);
break;
case ConstModel.checkboxButtonType:
CreateCheckboxButton(gridAutoLayout, controlTag, this.GetJPropertyValue(item, ConstModel.valueKey), rowIndex);
break;
case ConstModel.intType:
CreateNumericControl(gridAutoLayout, controlTag, item, rowIndex, typeValue);
break;
case ConstModel.floatType:
CreateNumericControl(gridAutoLayout, controlTag, item, rowIndex, typeValue);
break;
case ConstModel.stringType:
CreateTextBox(gridAutoLayout, controlTag, item,this.GetJPropertyValue(item, ConstModel.valueKey), rowIndex);
break;
case ConstModel.intRangeType:
CreateRangeControl(gridAutoLayout, controlTag, item, rowIndex, typeValue);
break;
case ConstModel.floatRangeType:
CreateRangeControl(gridAutoLayout, controlTag, item, rowIndex, typeValue);
break;
case ConstModel.checkboxType:
CreateCheckBoxsControl(gridAutoLayout, controlTag, item, rowIndex);
break;
case ConstModel.filePathType:
CreateFilePathControl(gridAutoLayout, controlTag, item, rowIndex);
break;
}
rowIndex++;
}
}
}
}
catch (Exception ex)
{
Logger.GetInstance().log.Error(ex.ToString());
}
}
private string GetJPropertyValue(JToken jToken,string jPropertyName)
{
JProperty jProperty = jToken.Values().Cast<JProperty>().Where(n => n.Name == jPropertyName).First();
return jProperty.Value.ToString();
}
private string GetCurrentJObjectStr(string jPropertyName, object value, string setKey)
{
this.SetJPropertyValue(currentJToken.Children().First().Children(), jPropertyName, value, setKey);
return JsonConvert.SerializeObject(currentJToken);
}
private void SetJPropertyValue(JEnumerable<JToken> jTokens, string jPropertyName,object value,string setKey)
{
JProperty jProperty = jTokens.Cast<JProperty>().Where(n => n.Name == jPropertyName).First();
JProperty jValueProperty = jProperty.Values().Cast<JProperty>().Where(n => n.Name == setKey).First();
this.SetValue(jValueProperty, value);
}
private void SetValue(JProperty jValueProperty,object value)
{
if (value.GetType().Name == "Single")
{
jValueProperty.Value = (float)value;
}
else if (value.GetType().Name == "Boolean")
{
jValueProperty.Value = (bool)value;
}
else if (value.GetType().Name == "Int32")
{
jValueProperty.Value = (int)value;
}
else
{
jValueProperty.Value = value.ToString();
}
}
private void SetIntNumericTextBoxValue(object sender, string setKey)
{
TextBox tb = sender as TextBox;
if (tb != null && tb.Tag != null)
{
string jPropertyName = tb.Tag.ToString();
string txtValue = tb.Text;
this.SetIntNumericTextBoxValue(jPropertyName, ConvertToInt(txtValue), setKey);
}
}
private void SetIntNumericTextBoxValue(string jPropertyName, int value, string setKey)
{
string old = GetTextBoxOldValue(jPropertyName, setKey);
if (old == value.ToString())
{
return;
}
string strCurrentJObject = this.GetCurrentJObjectStr(jPropertyName, value, setKey);
if (!this.SetConfig(strCurrentJObject))
{
//Box框周围变红
//numericControl.BorderThickness = new Thickness(0);
}
}
private void SendFloatNumericTextBoxValue(object sender, string setKey)
{
TextBox tb = sender as TextBox;
if (tb != null && tb.Tag != null)
{
string jPropertyName = tb.Tag.ToString();
string txtValue = tb.Text;
this.SendFloatNumericTextBoxValue(jPropertyName, ConvertToFloat(txtValue), setKey);
}
}
private void SendFloatNumericTextBoxValue(string jPropertyName, float value, string setKey)
{
string old = GetTextBoxOldValue(jPropertyName, setKey);
string _increment = "0.01";
string[] arrNum = _increment.Split(new char[] { ‘.‘ }, StringSplitOptions.RemoveEmptyEntries);
int count = arrNum.Length > 1 ? arrNum[1].Length : 0;
old = Math.Round(double.Parse(old), count).ToString();
if (old == value.ToString())
{
return;
}
string strCurrentJObject = this.GetCurrentJObjectStr(jPropertyName, value, setKey);
if (!this.SetConfig(strCurrentJObject))
{
//Box框周围变红
}
}
private void SendFilePathControlValue(string jPropertyName, string value, string setKey)
{
string old = GetTextBoxOldValue(jPropertyName, setKey);
if (old == value)
{
return;
}
string strCurrentJObject = this.GetCurrentJObjectStr(jPropertyName, value, setKey);
if (!this.SetConfig(strCurrentJObject))
{
//Box框周围变红
}
}
/// <summary>
/// 下发TextBox框的内容之前先看下内容比较之前有没有发生变化,没发生变化则不需要下发
/// </summary>
/// <param name="jPropertyName">二级节点名</param>
/// <returns></returns>
private string GetTextBoxOldValue(string jPropertyName, string setKey)
{
JEnumerable<JToken> jTokens = currentJToken.Children().First().Children();
JToken jToken = jTokens.Cast<JProperty>().Where(n => n.Name == jPropertyName).First();
return jToken.Values().Cast<JProperty>().Where(n => n.Name == setKey).First().Value.ToString();
}
private bool SetConfig(string strCurrentJObject)
{
try
{
if (string.IsNullOrEmpty(this.allCameraNo))
{
string leftStr = string.IsNullOrEmpty(this.cameraNo) ? "{" : "{\"cameraSerial\":" + "\"" + this.cameraNo + "\",";
strCurrentJObject = leftStr + strCurrentJObject + "}";
}
else
{
strCurrentJObject = "{\"cameraSerial\":" + "\"" + this.allCameraNo + "\"," + strCurrentJObject + "}";
}
string result = this.SetConfigFunc(strCurrentJObject);
JObject resultJObject = (JObject)JsonConvert.DeserializeObject(result);
if (resultJObject == null || resultJObject["result"] == null
|| resultJObject["result"]["errorCode"] == null
|| (float)resultJObject["result"]["errorCode"] != 0)
{
Logger.GetInstance().log.Error(string.Format("[Method={0},Result={1}] Set Method Failed", SetConfigFunc.Method.ToString(), result));
return false;
}
}
catch(Exception ex)
{
Logger.GetInstance().log.Error(ex.ToString());
return false;
}
return true;
}
private int ConvertToInt(string value)
{
int result = 0;
int.TryParse(value, out result);
return result;
}
private float ConvertToFloat(string value)
{
float result = 0;
float.TryParse(value, out result);
return result;
}
private bool ConvertToBool(string value)
{
bool result = false;
bool.TryParse(value, out result);
return result;
}
#endregion
#region 创建控件
private void CreateLabel(Grid grid, string text, int rowIndex, bool isBold)
{
try
{
TextBlock label = new TextBlock();
//存图页面父类标签加粗
if (this.isSaveImage && isBold)
{
label.FontWeight = FontWeights.Bold;
}
label.Text = LanguageResources.GetInstance().GetResource(text).ToString();
label.SetValue(Grid.RowProperty, rowIndex);
label.VerticalAlignment = System.Windows.VerticalAlignment.Center;
if (this.Resources != null)
{
label.Style = this.Resources["ParamKeyTBStyle"] as Style;
}
label.TextTrimming = TextTrimming.CharacterEllipsis;
label.ToolTip = label.Text;
grid.Children.Add(label);
}
catch (Exception ex)
{
Logger.GetInstance().log.Error(ex.ToString());
}
}
private void CreateCameraNameLabel(Grid grid, int rowIndex)
{
try
{
TextBlock label = new TextBlock();
label.FontWeight = FontWeights.Bold;
label.Text = this.cameraName;
label.SetValue(Grid.RowProperty, rowIndex);
label.VerticalAlignment = System.Windows.VerticalAlignment.Center;
if (this.Resources != null)
{
label.Style = this.Resources["ParamKeyTBStyle"] as Style;
}
label.TextTrimming = TextTrimming.CharacterEllipsis;
label.ToolTip = label.Text;
grid.Children.Add(label);
}
catch (Exception ex)
{
Logger.GetInstance().log.Error(ex.ToString());
}
}
private void CreateComboBox(Grid grid, string key, JToken jToken, int rowIndex)
{
try
{
ComboBox comboBox = new ComboBox();
comboBox.SetValue(Grid.RowProperty, rowIndex);
comboBox.SetValue(Grid.ColumnProperty, 2);
comboBox.HorizontalAlignment = HorizontalAlignment.Left;
comboBox.VerticalAlignment = VerticalAlignment.Center;
comboBox.Width = ConstModel.controlWidth;
comboBox.Height = ConstModel.controlHeight;
if (Application.Current != null && Application.Current.Resources != null)
{
comboBox.Style = Application.Current.Resources["ComboBoxStyle"] as Style;
}
comboBox.SelectionChanged += ComboBox_SelectionChanged;
List<string> valueList = this.GetJPropertyValue(jToken, ConstModel.valuesKey).Split(‘,‘).ToList();
string content = string.Empty;
object resourceObj = null;
foreach (string tmp in valueList)
{
ComboBoxItem item = new ComboBoxItem();
content = tmp.Trim();
resourceObj = LanguageResources.GetInstance().GetResource(content);
if (resourceObj == null)
{
item.Content = content;
}
else
{
item.Content = resourceObj.ToString();
if (!enzhDic.ContainsKey(resourceObj.ToString()))
{
enzhDic.Add(resourceObj.ToString(), content);
}
}
item.Content = resourceObj == null ? content : resourceObj.ToString();
if (comboBox.Items != null)
{
comboBox.Items.Add(item);
}
}
string value = this.GetJPropertyValue(jToken, ConstModel.valueKey);
content = value;
resourceObj = LanguageResources.GetInstance().GetResource(content);
comboBox.Text = resourceObj == null ? content : resourceObj.ToString();
comboBox.Tag = key;
grid.Children.Add(comboBox);
}
catch (Exception ex)
{
Logger.GetInstance().log.Error(ex.ToString());
}
}
private void CreateCheckbox(Grid grid, string key, string value, int rowIndex)
{
try
{
CheckBox checkBox = new CheckBox();
checkBox.SetValue(Grid.RowProperty, rowIndex);
checkBox.SetValue(Grid.ColumnProperty, 2);
checkBox.HorizontalAlignment = HorizontalAlignment.Left;
checkBox.VerticalAlignment = VerticalAlignment.Center;
checkBox.Width = 50;
checkBox.Height = ConstModel.controlHeight;
checkBox.IsChecked = this.ConvertToBool(value);
checkBox.Tag = key;
if (Application.Current != null && Application.Current.Resources != null)
{
checkBox.Style = Application.Current.Resources["chkBullet"] as Style;
}
checkBox.Checked += CheckBox_CheckStatusChanged;
checkBox.Unchecked += CheckBox_CheckStatusChanged;
grid.Children.Add(checkBox);
}
catch (Exception ex)
{
Logger.GetInstance().log.Error(ex.ToString());
}
}
private void CreateCheckboxButton(Grid grid, string key, string value, int rowIndex)
{
try
{
CheckBox checkBoxButton = new CheckBox();
checkBoxButton.Content = LanguageResources.GetInstance().GetResource(key).ToString();
checkBoxButton.SetValue(Grid.RowProperty, rowIndex);
checkBoxButton.SetValue(Grid.ColumnProperty, 2);
checkBoxButton.HorizontalAlignment = HorizontalAlignment.Left;
checkBoxButton.VerticalAlignment = VerticalAlignment.Center;
checkBoxButton.Width = 150;
checkBoxButton.Height = ConstModel.controlHeight;
checkBoxButton.IsChecked = this.ConvertToBool(value);
checkBoxButton.Tag = key;
if (Application.Current != null && Application.Current.Resources != null)
{
checkBoxButton.Style = Application.Current.Resources["CommonChechBox3"] as Style;
}
checkBoxButton.Checked += CheckBoxButton_CheckStatusChanged;
checkBoxButton.Unchecked += CheckBoxButton_CheckStatusChanged;
grid.Children.Add(checkBoxButton);
}
catch (Exception ex)
{
Logger.GetInstance().log.Error(ex.ToString());
}
}
private void CreateNumericControl(Grid grid, string key,JToken jToken, int rowIndex,string typeValue)
{
try
{
NumericControl controlNum = new NumericControl();
controlNum.SetValue(Grid.RowProperty, rowIndex);
controlNum.SetValue(Grid.ColumnProperty, 2);
controlNum.HorizontalAlignment = HorizontalAlignment.Left;
controlNum.VerticalAlignment = VerticalAlignment.Center;
controlNum.Width = ConstModel.controlWidth;
controlNum.Height = ConstModel.controlHeight;
//controlNum.Margin = new Thickness(100, 0, 0, 0);
if (typeValue == "int")
{
controlNum.MinValue = ConvertToInt(this.GetJPropertyValue(jToken, ConstModel.minKey));
controlNum.MaxValue = ConvertToInt(this.GetJPropertyValue(jToken, ConstModel.maxKey));
controlNum.Increment = 1;
controlNum.Value = ConvertToInt(this.GetJPropertyValue(jToken, ConstModel.valueKey));
controlNum.ValueText.LostFocus += IntNumericTextBox_LostFocus;
controlNum.ValueText.KeyDown += IntNumericTextBox_KeyDown;
controlNum.ValueChanged += IntNumericValueChanged;
}
else
{
controlNum.MinValue = ConvertToFloat(this.GetJPropertyValue(jToken, ConstModel.minKey));
controlNum.MaxValue = ConvertToFloat(this.GetJPropertyValue(jToken, ConstModel.maxKey));
//每次缩进必须在赋值之前,否则float数值会显示int数值
controlNum.Increment = 0.01;
controlNum.Value = ConvertToFloat(this.GetJPropertyValue(jToken, ConstModel.valueKey));
controlNum.ValueText.LostFocus += FloatNumericTextBox_LostFocus;
controlNum.ValueText.KeyDown += FloatNumericTextBox_KeyDown;
controlNum.ValueChanged += FloatNumericValueChanged;
}
controlNum.Tag = key;
controlNum.ValueText.Tag = key;
grid.Children.Add(controlNum);
}
catch (Exception ex)
{
Logger.GetInstance().log.Error(ex.ToString());
}
}
private void CreateTextBox(Grid grid, string key, JToken jToken, string text, int rowIndex)
{
try
{
TextBox textBox = new TextBox();
textBox.Text = text;
textBox.Tag = key;
textBox.Width = ConstModel.controlWidth;
textBox.SetValue(Grid.RowProperty, rowIndex);
textBox.SetValue(Grid.ColumnProperty, 2);
textBox.VerticalAlignment = VerticalAlignment.Center;
textBox.HorizontalAlignment = HorizontalAlignment.Left;
if (Application.Current != null && Application.Current.Resources != null)
{
textBox.Style = Application.Current.Resources["CommonTextBoxStyle"] as Style;
}
if (!textBoxOldValueDic.ContainsKey(key))
{
textBoxOldValueDic.Add(key, text);
}
//重量模块的输入字符串和标识符不让输入中文,其他地方的TextBox可以输入中文
if (key == ConstModel.inStringKey || key == ConstModel.iDentifierKey)
{
System.Windows.Input.InputMethod.SetIsInputMethodEnabled(textBox, false);
}
textBox.MaxLength = ConvertToInt(this.GetJPropertyValue(jToken, ConstModel.maxKey));
textBox.TextChanged += TextBox_TextChanged;
textBox.LostFocus += TextBox_LostFocus;
textBox.KeyDown += TextBox_KeyDown;
grid.Children.Add(textBox);
}
catch (Exception ex)
{
Logger.GetInstance().log.Error(ex.ToString());
}
}
private void CreateRangeControl(Grid grid, string key, JToken jToken, int rowIndex, string typeValue)
{
try
{
RangeControl rangeControl = new RangeControl();
rangeControl.SetValue(Grid.RowProperty, rowIndex);
rangeControl.SetValue(Grid.ColumnProperty, 2);
rangeControl.HorizontalAlignment = HorizontalAlignment.Left;
rangeControl.VerticalAlignment = VerticalAlignment.Center;
rangeControl.Height = ConstModel.controlHeight;
if (typeValue == "intRange")
{
rangeControl.LeftMinValue = ConvertToInt(this.GetJPropertyValue(jToken, ConstModel.minKey));
rangeControl.LeftMaxValue = ConvertToInt(this.GetJPropertyValue(jToken, ConstModel.maxKey));
rangeControl.RightMinValue = ConvertToInt(this.GetJPropertyValue(jToken, ConstModel.minKey));
rangeControl.RightMaxValue = ConvertToInt(this.GetJPropertyValue(jToken, ConstModel.maxKey));
rangeControl.Increment = 1;
rangeControl.LeftValue = ConvertToInt(this.GetJPropertyValue(jToken, ConstModel.leftValueKey));
rangeControl.RightValue = ConvertToInt(this.GetJPropertyValue(jToken, ConstModel.rightValueKey));
rangeControl.LeftNumericControl.ValueText.LostFocus += IntRangeLeftTextBox_LostFocus;
rangeControl.LeftNumericControl.ValueText.KeyDown += IntRangeLeftTextBox_KeyDown;
rangeControl.LeftNumericControl.ValueChanged += IntRangeLeftValueChanged;
rangeControl.RightNumericControl.ValueText.LostFocus += IntRangeRightTextBox_LostFocus;
rangeControl.RightNumericControl.ValueText.KeyDown += IntRangeRightTextBox_KeyDown;
rangeControl.RightNumericControl.ValueChanged += IntRangeRightValueChanged;
}
else
{
rangeControl.LeftMinValue = ConvertToFloat(this.GetJPropertyValue(jToken, ConstModel.minKey));
rangeControl.LeftMaxValue = ConvertToFloat(this.GetJPropertyValue(jToken, ConstModel.maxKey));
rangeControl.RightMinValue = ConvertToFloat(this.GetJPropertyValue(jToken, ConstModel.minKey));
rangeControl.RightMaxValue = ConvertToFloat(this.GetJPropertyValue(jToken, ConstModel.maxKey));
//每次缩进必须在赋值之前,否则float数值会显示int数值
rangeControl.Increment = 0.01;
rangeControl.LeftValue = ConvertToFloat(this.GetJPropertyValue(jToken, ConstModel.leftValueKey));
rangeControl.RightValue = ConvertToFloat(this.GetJPropertyValue(jToken, ConstModel.rightValueKey));
rangeControl.LeftNumericControl.ValueText.LostFocus += FloatRangeLeftTextBox_LostFocus;
rangeControl.LeftNumericControl.ValueText.KeyDown += FloatRangeLeftTextBox_KeyDown;
rangeControl.LeftNumericControl.ValueChanged += FloatRangeLeftValueChanged;
rangeControl.RightNumericControl.ValueText.LostFocus += FloatRangeRightTextBox_LostFocus;
rangeControl.RightNumericControl.ValueText.KeyDown += FloatRangeRightTextBox_KeyDown;
rangeControl.RightNumericControl.ValueChanged += FloatRangeRightValueChanged;
}
rangeControl.LeftNumericControl.ValueText.Tag = key;
rangeControl.RightNumericControl.ValueText.Tag = key;
grid.Children.Add(rangeControl);
}
catch (Exception ex)
{
Logger.GetInstance().log.Error(ex.ToString());
}
}
private void CreateCheckBoxsControl(Grid grid, string key, JToken jToken, int rowIndex)
{
try
{
string values = this.GetJPropertyValue(jToken, ConstModel.valuesKey);
string selectValues = this.GetJPropertyValue(jToken, ConstModel.valueKey);
CheckBoxsControl checkBoxsControl = new CheckBoxsControl(values, selectValues, ModuleCheckBox_CheckStatusChanged);
checkBoxsControl.SetValue(Grid.RowProperty, rowIndex);
checkBoxsControl.SetValue(Grid.ColumnProperty, 2);
checkBoxsControl.HorizontalAlignment = HorizontalAlignment.Left;
checkBoxsControl.VerticalAlignment = VerticalAlignment.Center;
checkBoxsControl.Width = ConstModel.controlWidth;
checkBoxsControl.Tag = key;
grid.Children.Add(checkBoxsControl);
}
catch (Exception ex)
{
Logger.GetInstance().log.Error(ex.ToString());
}
}
private void CreateFilePathControl(Grid grid, string key, JToken jToken, int rowIndex)
{
try
{
TextBOXANDButtonUserControl filePathControl = new TextBOXANDButtonUserControl();
filePathControl.SetValue(Grid.RowProperty, rowIndex);
filePathControl.SetValue(Grid.ColumnProperty, 2);
filePathControl.HorizontalAlignment = HorizontalAlignment.Left;
filePathControl.VerticalAlignment = VerticalAlignment.Center;
filePathControl.Width = ConstModel.controlWidth;
filePathControl.Height = ConstModel.controlHeight;
string fileNames = this.GetJPropertyValue(jToken, "fileNames");
if (string.IsNullOrEmpty(fileNames))
{
filePathControl.OpenFileType = "2";
//文件夹路径选择有最大长度限制
filePathControl.MaxLength = ConvertToInt(this.GetJPropertyValue(jToken, ConstModel.maxKey));
}
else
{
filePathControl.OpenFileType = "3";
string[] fileNameArray = fileNames.Split(‘,‘);
foreach (string fileName in fileNameArray)
{
filePathControl.FileFilter = string.Format("{0}{1}", filePathControl.FileFilter, string.Format("{0}|{1}", fileName, fileName));
}
}
filePathControl.ValueText.Tag = key;
filePathControl.Value = this.GetJPropertyValue(jToken, ConstModel.valueKey);
filePathControl.ValueChanged += FilePathControlValueChanged;
grid.Children.Add(filePathControl);
}
catch (Exception ex)
{
Logger.GetInstance().log.Error(ex.ToString());
}
}
#endregion
#region 控件事件
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//根据对象的tag标签找到currentJObject中对应的节点,对节点修改再序列化调用Set方法
ComboBox comboBox = sender as ComboBox;
if (comboBox != null)
{
object tag = comboBox.Tag;
if (tag != null)
{
string jPropertyName = tag.ToString();
if (comboBox.SelectedItem != null)
{
ComboBoxItem comboBoxItem = comboBox.SelectedItem as ComboBoxItem;
if (comboBoxItem != null && comboBoxItem.Content != null)
{
//中文转英文字段处理
string value = comboBoxItem.Content.ToString();
string enValue = string.Empty;
if (enzhDic.TryGetValue(value, out enValue))
{
value = enValue;
}
string strCurrentJObject = this.GetCurrentJObjectStr(jPropertyName, value, ConstModel.valueKey);
if (this.SetConfig(strCurrentJObject))
{
this.ReloadControls();
}
}
}
}
}
}
private void CheckBox_CheckStatusChanged(object sender, RoutedEventArgs e)
{
CheckBox cb = sender as CheckBox;
if (cb != null && cb.Tag != null)
{
string jPropertyName = cb.Tag.ToString();
bool value = (bool)cb.IsChecked;
string strCurrentJObject = this.GetCurrentJObjectStr(jPropertyName, value, ConstModel.valueKey);
if (this.SetConfig(strCurrentJObject))
{
if (this.ReloadAutoLayoutPage != null)
{
if (jPropertyName == ConstModel.weightModuleEnable || jPropertyName == ConstModel.FixedWeightEnable
|| jPropertyName == ConstModel.plcWeightEnable)
{
this.ReloadAutoLayoutPage();
}
else
{
this.ReloadControls();
}
}
else
{
this.ReloadControls();
}
}
}
}
private void CheckBoxButton_CheckStatusChanged(object sender, RoutedEventArgs e)
{
CheckBox cb = sender as CheckBox;
if (cb != null && cb.Tag != null)
{
string jPropertyName = cb.Tag.ToString();
bool value = (bool)cb.IsChecked;
string strCurrentJObject = this.GetCurrentJObjectStr(jPropertyName, value, ConstModel.valueKey);
if (this.SetConfig(strCurrentJObject))
{
if (this.ReloadAutoLayoutPage != null)
{
if (jPropertyName == ConstModel.weightModuleEnable || jPropertyName == ConstModel.FixedWeightEnable
|| jPropertyName == ConstModel.plcWeightEnable)
{
this.ReloadAutoLayoutPage();
}
else
{
this.ReloadControls();
}
}
else
{
this.ReloadControls();
}
}
}
}
private void ModuleCheckBox_CheckStatusChanged(string jPropertyName, string value)
{
string strCurrentJObject = this.GetCurrentJObjectStr(jPropertyName, value, ConstModel.valueKey);
if (!this.SetConfig(strCurrentJObject))
{
//Box框周围变红
}
}
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox tb = sender as TextBox;
if (tb != null && tb.Tag != null)
{
if (textBoxOldValueDic.ContainsKey(tb.Tag.ToString()))
{
if (!string.IsNullOrEmpty(tb.Text))
{
textBoxOldValueDic[tb.Tag.ToString()] = tb.Text;
}
}
}
}
private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
SendTextBoxValue(sender);
}
}
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
TextBox tb = sender as TextBox;
if (tb != null)
{
if (string.IsNullOrEmpty(tb.Text))
{
string text = string.Empty;
if (tb.Tag != null)
{
if (textBoxOldValueDic.TryGetValue(tb.Tag.ToString(), out text))
{
tb.Text = text;
tb.SelectionStart = tb.Text.Length;
}
}
}
}
SendTextBoxValue(sender);
}
private void SendTextBoxValue(object sender)
{
TextBox textBox = (sender as TextBox);
if (textBox != null)
{
if (textBox.Tag != null)
{
string jPropertyName = textBox.Tag.ToString();
string old = GetTextBoxOldValue(jPropertyName, ConstModel.valueKey);
string value = (sender as TextBox).Text;
if (old == value)
{
return;
}
string strCurrentJObject = this.GetCurrentJObjectStr(jPropertyName, value, ConstModel.valueKey);
if (!this.SetConfig(strCurrentJObject))
{
//Box框周围变红
//textBox.BorderThickness = new Thickness(0);
}
}
}
}
private void IntNumericTextBox_LostFocus(object sender, RoutedEventArgs e)
{
SetIntNumericTextBoxValue(sender, ConstModel.valueKey);
}
private void IntNumericTextBox_KeyDown(object sender, KeyEventArgs e)
{
if(e.Key== Key.Enter)
{
SetIntNumericTextBoxValue(sender, ConstModel.valueKey);
}
}
private void FloatNumericTextBox_LostFocus(object sender, RoutedEventArgs e)
{
SendFloatNumericTextBoxValue(sender, ConstModel.valueKey);
}
private void FloatNumericTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
SendFloatNumericTextBoxValue(sender, ConstModel.valueKey);
}
}
private void IntNumericValueChanged(object sender)
{
SetIntNumericTextBoxValue(sender, ConstModel.valueKey);
}
private void FloatNumericValueChanged(object sender)
{
SendFloatNumericTextBoxValue(sender, ConstModel.valueKey);
}
private void FilePathControlValueChanged(object sender)
{
TextBox tb = sender as TextBox;
if (tb != null && tb.Tag != null)
{
this.SendFilePathControlValue(tb.Tag.ToString(), tb.Text, ConstModel.valueKey);
}
}
#region Range控件Textbox事件
private void IntRangeLeftTextBox_LostFocus(object sender, RoutedEventArgs e)
{
SetIntNumericTextBoxValue(sender, ConstModel.leftValueKey);
}
private void IntRangeLeftTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
SetIntNumericTextBoxValue(sender, ConstModel.leftValueKey);
}
}
private void IntRangeRightTextBox_LostFocus(object sender, RoutedEventArgs e)
{
SetIntNumericTextBoxValue(sender, ConstModel.rightValueKey);
}
private void IntRangeRightTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
SetIntNumericTextBoxValue(sender, ConstModel.rightValueKey);
}
}
private void FloatRangeLeftTextBox_LostFocus(object sender, RoutedEventArgs e)
{
SendFloatNumericTextBoxValue(sender, ConstModel.leftValueKey);
}
private void FloatRangeLeftTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
SendFloatNumericTextBoxValue(sender, ConstModel.leftValueKey);
}
}
private void FloatRangeRightTextBox_LostFocus(object sender, RoutedEventArgs e)
{
SendFloatNumericTextBoxValue(sender, ConstModel.rightValueKey);
}
private void FloatRangeRightTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
SendFloatNumericTextBoxValue(sender, ConstModel.rightValueKey);
}
}
private void IntRangeLeftValueChanged(object sender)
{
SetIntNumericTextBoxValue(sender, ConstModel.leftValueKey);
}
private void IntRangeRightValueChanged(object sender)
{
SetIntNumericTextBoxValue(sender, ConstModel.rightValueKey);
}
private void FloatRangeLeftValueChanged(object sender)
{
SendFloatNumericTextBoxValue(sender, ConstModel.leftValueKey);
}
private void FloatRangeRightValueChanged(object sender)
{
SendFloatNumericTextBoxValue(sender, ConstModel.rightValueKey);
}
#endregion
#endregion
}
}
using CMSystemSetModule.Model.CameraConfig;using CMSystemSetModule.Model.Common;using CMSystemSetModule.ResourcesManger;using CMSystemSetModule.Utils;using Newtonsoft.Json;using Newtonsoft.Json.Linq;using System;using System.Collections.Generic;using System.Linq;using System.Windows;using System.Windows.Controls;using System.Windows.Input;
namespace CMSystemSetModule.UserControls{ /// <summary> /// AutoLayoutControl.xaml 的交互逻辑 /// </summary> public partial class AutoLayoutControl : UserControl { #region 全局变量 private string cameraNo; private string cameraName; //用于工业相机算法界面的全部相机 private string allCameraNo; private JToken originalJToken; private JToken currentJToken; private Func<string> GetConfigFunc; private Func<string, string> GetCameraConfigFunc; private Func<string, string> SetConfigFunc; private Action ReloadAutoLayoutPage; //存图页面父类标签需要加粗 private bool isSaveImage; //部分参数中英文转换字典 private Dictionary<string, string> enzhDic = new Dictionary<string, string>(); //输入框原来的值,用于最小值复原 private Dictionary<string, string> textBoxOldValueDic = new Dictionary<string, string>(); public bool IsContentChanaged { get { //考虑到下发失败的情况,因此currentJToken需要获取底层模块的数据再比较,以底层数据为准 currentJToken = this.GetCurrentJToken(); if (currentJToken == null || originalJToken == null) { return false; } return !(this.originalJToken.ToString() == this.currentJToken.ToString()); } } #endregion
#region 构造函数 private AutoLayoutControl(Func<string, string> SetConfigFunc) { InitializeComponent(); this.SetConfigFunc = SetConfigFunc; }
public AutoLayoutControl(Func<string> GetConfigFunc, Func<string, string> SetConfigFunc, Action ReloadAutoLayoutPage, bool isSaveImage) :this(SetConfigFunc) { this.GetConfigFunc = GetConfigFunc; this.ReloadAutoLayoutPage = ReloadAutoLayoutPage; this.isSaveImage = isSaveImage; //originalJToken = this.GetJToken(); //ReloadControls(); }
public AutoLayoutControl(Func<string, string> GetCameraConfigFunc, Func<string, string> SetConfigFunc, string cameraNo, string cameraName) : this(SetConfigFunc) { this.GetCameraConfigFunc = GetCameraConfigFunc; this.cameraNo = cameraNo; this.cameraName = cameraName; originalJToken = this.GetCameraJToken(this.cameraNo); ReloadControls(); } /// <summary> /// 只有工业相机算法页面会调用,因为涉及到全部相机这种类型 /// </summary> /// <param name="GetCameraConfigFunc"></param> /// <param name="SetConfigFunc"></param> /// <param name="cameraNo"></param> /// <param name="allCameraNo"></param> public AutoLayoutControl(Func<string, string> GetCameraConfigFunc, Func<string, string> SetConfigFunc, string cameraNo, string cameraName, string allCameraNo) : this(SetConfigFunc) { this.GetCameraConfigFunc = GetCameraConfigFunc; this.cameraNo = cameraNo; this.allCameraNo = allCameraNo; originalJToken = this.GetCameraJToken(this.cameraNo); ReloadControls(); } #endregion
#region 方法 public bool Save() { currentJToken = this.GetCurrentJToken(); //原始数据刷新到当前数据即可 this.originalJToken = this.currentJToken == null ? null : this.currentJToken.DeepClone(); return true; } public void Back() { if (this.originalJToken != null && this.currentJToken != null) { //没有修改过不需要回滚 if (this.originalJToken.ToString() != this.currentJToken.ToString()) { this.currentJToken = this.originalJToken.DeepClone(); string strCurrentJObject = JsonConvert.SerializeObject(currentJToken); this.SetConfig(strCurrentJObject); } } } public void InitOriginalJToken() { originalJToken = this.GetJToken(); } private JToken GetCurrentJToken() { if (GetConfigFunc != null) { currentJToken = this.GetJToken(); } else if (GetCameraConfigFunc != null) { currentJToken = this.GetCameraJToken(this.cameraNo); } return currentJToken; } private JToken GetJToken() { if (GetConfigFunc != null) { string strConfig = GetConfigFunc(); JObject jObject = (JObject)JsonConvert.DeserializeObject(strConfig); if (jObject == null) { return null; } if (jObject["result"] != null && jObject["result"].First != null) { return jObject["result"].First as JToken; } } return null; } private JToken GetCameraJToken(string cameraNo) { try { if (GetCameraConfigFunc != null) { CameraSerialModel model = new CameraSerialModel(); model.cameraSerial = cameraNo; string strConfig = GetCameraConfigFunc(JsonConvert.SerializeObject(model)); JObject jObject = (JObject)JsonConvert.DeserializeObject(strConfig); if (jObject == null) { return null; } if (jObject["result"] != null && jObject["result"].First != null) { return jObject["result"].First as JToken; } } } catch (Exception ex) { Logger.GetInstance().log.Error(ex.ToString()); } return null; } public void ReloadControls() { try { //新建控件花了0.08秒(16个控件) gridAutoLayout.Children.RemoveRange(0, gridAutoLayout.Children.Count); gridAutoLayout.RowDefinitions.Clear(); if (GetConfigFunc != null) { currentJToken = this.GetJToken(); this.CreateControls(currentJToken); } else if (GetCameraConfigFunc != null) { currentJToken = this.GetCameraJToken(this.cameraNo); this.CreateControls(currentJToken); } } catch (Exception ex) { Logger.GetInstance().log.Error(ex.ToString()); } } private void CreateControls(JToken jToken) { try { if (jToken != null) { JEnumerable<JToken> jTokens = jToken.Children().First().Children(); int rowIndex = 0; //加粗存图模块父类节点 bool isBold = true; foreach (JToken item in jTokens) { string typeValue = this.GetJPropertyValue(item, ConstModel.typeKey); RowDefinition row = new RowDefinition(); int rowheight = ConstModel.rowHeight; if (typeValue == ConstModel.checkboxType) { rowheight = 96; } row.Height = new GridLength(rowheight); gridAutoLayout.RowDefinitions.Add(row); if ((item as JProperty) != null) { string controlTag = (item as JProperty).Name; if (typeValue == ConstModel.checkboxButtonType) { CreateCameraNameLabel(gridAutoLayout, rowIndex); } else { //这里名称要从字段转换为中文标签,在资源文件中对应 CreateLabel(gridAutoLayout, controlTag, rowIndex, isBold); } isBold = false; switch (typeValue) { case ConstModel.enumType: CreateComboBox(gridAutoLayout, controlTag, item, rowIndex); break; case ConstModel.boolType: CreateCheckbox(gridAutoLayout, controlTag, this.GetJPropertyValue(item, ConstModel.valueKey), rowIndex); break; case ConstModel.checkboxButtonType: CreateCheckboxButton(gridAutoLayout, controlTag, this.GetJPropertyValue(item, ConstModel.valueKey), rowIndex); break; case ConstModel.intType: CreateNumericControl(gridAutoLayout, controlTag, item, rowIndex, typeValue); break; case ConstModel.floatType: CreateNumericControl(gridAutoLayout, controlTag, item, rowIndex, typeValue); break; case ConstModel.stringType: CreateTextBox(gridAutoLayout, controlTag, item,this.GetJPropertyValue(item, ConstModel.valueKey), rowIndex); break; case ConstModel.intRangeType: CreateRangeControl(gridAutoLayout, controlTag, item, rowIndex, typeValue); break; case ConstModel.floatRangeType: CreateRangeControl(gridAutoLayout, controlTag, item, rowIndex, typeValue); break; case ConstModel.checkboxType: CreateCheckBoxsControl(gridAutoLayout, controlTag, item, rowIndex); break; case ConstModel.filePathType: CreateFilePathControl(gridAutoLayout, controlTag, item, rowIndex); break; } rowIndex++; } } } } catch (Exception ex) { Logger.GetInstance().log.Error(ex.ToString()); } } private string GetJPropertyValue(JToken jToken,string jPropertyName) { JProperty jProperty = jToken.Values().Cast<JProperty>().Where(n => n.Name == jPropertyName).First(); return jProperty.Value.ToString(); } private string GetCurrentJObjectStr(string jPropertyName, object value, string setKey) { this.SetJPropertyValue(currentJToken.Children().First().Children(), jPropertyName, value, setKey); return JsonConvert.SerializeObject(currentJToken); } private void SetJPropertyValue(JEnumerable<JToken> jTokens, string jPropertyName,object value,string setKey) { JProperty jProperty = jTokens.Cast<JProperty>().Where(n => n.Name == jPropertyName).First(); JProperty jValueProperty = jProperty.Values().Cast<JProperty>().Where(n => n.Name == setKey).First(); this.SetValue(jValueProperty, value); } private void SetValue(JProperty jValueProperty,object value) { if (value.GetType().Name == "Single") { jValueProperty.Value = (float)value; } else if (value.GetType().Name == "Boolean") { jValueProperty.Value = (bool)value; } else if (value.GetType().Name == "Int32") { jValueProperty.Value = (int)value; } else { jValueProperty.Value = value.ToString(); } } private void SetIntNumericTextBoxValue(object sender, string setKey) { TextBox tb = sender as TextBox; if (tb != null && tb.Tag != null) { string jPropertyName = tb.Tag.ToString(); string txtValue = tb.Text; this.SetIntNumericTextBoxValue(jPropertyName, ConvertToInt(txtValue), setKey); } } private void SetIntNumericTextBoxValue(string jPropertyName, int value, string setKey) { string old = GetTextBoxOldValue(jPropertyName, setKey); if (old == value.ToString()) { return; } string strCurrentJObject = this.GetCurrentJObjectStr(jPropertyName, value, setKey);
if (!this.SetConfig(strCurrentJObject)) { //Box框周围变红 //numericControl.BorderThickness = new Thickness(0); } } private void SendFloatNumericTextBoxValue(object sender, string setKey) { TextBox tb = sender as TextBox; if (tb != null && tb.Tag != null) { string jPropertyName = tb.Tag.ToString(); string txtValue = tb.Text; this.SendFloatNumericTextBoxValue(jPropertyName, ConvertToFloat(txtValue), setKey); } } private void SendFloatNumericTextBoxValue(string jPropertyName, float value, string setKey) { string old = GetTextBoxOldValue(jPropertyName, setKey);
string _increment = "0.01"; string[] arrNum = _increment.Split(new char[] { ‘.‘ }, StringSplitOptions.RemoveEmptyEntries); int count = arrNum.Length > 1 ? arrNum[1].Length : 0; old = Math.Round(double.Parse(old), count).ToString();
if (old == value.ToString()) { return; } string strCurrentJObject = this.GetCurrentJObjectStr(jPropertyName, value, setKey); if (!this.SetConfig(strCurrentJObject)) { //Box框周围变红 } } private void SendFilePathControlValue(string jPropertyName, string value, string setKey) { string old = GetTextBoxOldValue(jPropertyName, setKey); if (old == value) { return; } string strCurrentJObject = this.GetCurrentJObjectStr(jPropertyName, value, setKey); if (!this.SetConfig(strCurrentJObject)) { //Box框周围变红 } } /// <summary> /// 下发TextBox框的内容之前先看下内容比较之前有没有发生变化,没发生变化则不需要下发 /// </summary> /// <param name="jPropertyName">二级节点名</param> /// <returns></returns> private string GetTextBoxOldValue(string jPropertyName, string setKey) { JEnumerable<JToken> jTokens = currentJToken.Children().First().Children(); JToken jToken = jTokens.Cast<JProperty>().Where(n => n.Name == jPropertyName).First(); return jToken.Values().Cast<JProperty>().Where(n => n.Name == setKey).First().Value.ToString(); } private bool SetConfig(string strCurrentJObject) { try { if (string.IsNullOrEmpty(this.allCameraNo)) { string leftStr = string.IsNullOrEmpty(this.cameraNo) ? "{" : "{\"cameraSerial\":" + "\"" + this.cameraNo + "\","; strCurrentJObject = leftStr + strCurrentJObject + "}"; } else { strCurrentJObject = "{\"cameraSerial\":" + "\"" + this.allCameraNo + "\"," + strCurrentJObject + "}"; } string result = this.SetConfigFunc(strCurrentJObject); JObject resultJObject = (JObject)JsonConvert.DeserializeObject(result); if (resultJObject == null || resultJObject["result"] == null || resultJObject["result"]["errorCode"] == null || (float)resultJObject["result"]["errorCode"] != 0) { Logger.GetInstance().log.Error(string.Format("[Method={0},Result={1}] Set Method Failed", SetConfigFunc.Method.ToString(), result)); return false; } } catch(Exception ex) { Logger.GetInstance().log.Error(ex.ToString()); return false; } return true; } private int ConvertToInt(string value) { int result = 0; int.TryParse(value, out result); return result; } private float ConvertToFloat(string value) { float result = 0; float.TryParse(value, out result); return result; } private bool ConvertToBool(string value) { bool result = false; bool.TryParse(value, out result); return result; }
#endregion
#region 创建控件 private void CreateLabel(Grid grid, string text, int rowIndex, bool isBold) { try { TextBlock label = new TextBlock(); //存图页面父类标签加粗 if (this.isSaveImage && isBold) { label.FontWeight = FontWeights.Bold; } label.Text = LanguageResources.GetInstance().GetResource(text).ToString(); label.SetValue(Grid.RowProperty, rowIndex); label.VerticalAlignment = System.Windows.VerticalAlignment.Center; if (this.Resources != null) { label.Style = this.Resources["ParamKeyTBStyle"] as Style; } label.TextTrimming = TextTrimming.CharacterEllipsis; label.ToolTip = label.Text; grid.Children.Add(label); } catch (Exception ex) { Logger.GetInstance().log.Error(ex.ToString()); } } private void CreateCameraNameLabel(Grid grid, int rowIndex) { try { TextBlock label = new TextBlock(); label.FontWeight = FontWeights.Bold; label.Text = this.cameraName; label.SetValue(Grid.RowProperty, rowIndex); label.VerticalAlignment = System.Windows.VerticalAlignment.Center; if (this.Resources != null) { label.Style = this.Resources["ParamKeyTBStyle"] as Style; } label.TextTrimming = TextTrimming.CharacterEllipsis; label.ToolTip = label.Text; grid.Children.Add(label); } catch (Exception ex) { Logger.GetInstance().log.Error(ex.ToString()); } } private void CreateComboBox(Grid grid, string key, JToken jToken, int rowIndex) { try { ComboBox comboBox = new ComboBox(); comboBox.SetValue(Grid.RowProperty, rowIndex); comboBox.SetValue(Grid.ColumnProperty, 2); comboBox.HorizontalAlignment = HorizontalAlignment.Left; comboBox.VerticalAlignment = VerticalAlignment.Center; comboBox.Width = ConstModel.controlWidth; comboBox.Height = ConstModel.controlHeight; if (Application.Current != null && Application.Current.Resources != null) { comboBox.Style = Application.Current.Resources["ComboBoxStyle"] as Style; } comboBox.SelectionChanged += ComboBox_SelectionChanged; List<string> valueList = this.GetJPropertyValue(jToken, ConstModel.valuesKey).Split(‘,‘).ToList(); string content = string.Empty; object resourceObj = null; foreach (string tmp in valueList) { ComboBoxItem item = new ComboBoxItem(); content = tmp.Trim(); resourceObj = LanguageResources.GetInstance().GetResource(content); if (resourceObj == null) { item.Content = content; } else { item.Content = resourceObj.ToString(); if (!enzhDic.ContainsKey(resourceObj.ToString())) { enzhDic.Add(resourceObj.ToString(), content); } } item.Content = resourceObj == null ? content : resourceObj.ToString(); if (comboBox.Items != null) { comboBox.Items.Add(item); } } string value = this.GetJPropertyValue(jToken, ConstModel.valueKey); content = value; resourceObj = LanguageResources.GetInstance().GetResource(content); comboBox.Text = resourceObj == null ? content : resourceObj.ToString(); comboBox.Tag = key; grid.Children.Add(comboBox); } catch (Exception ex) { Logger.GetInstance().log.Error(ex.ToString()); } } private void CreateCheckbox(Grid grid, string key, string value, int rowIndex) { try { CheckBox checkBox = new CheckBox(); checkBox.SetValue(Grid.RowProperty, rowIndex); checkBox.SetValue(Grid.ColumnProperty, 2); checkBox.HorizontalAlignment = HorizontalAlignment.Left; checkBox.VerticalAlignment = VerticalAlignment.Center; checkBox.Width = 50; checkBox.Height = ConstModel.controlHeight; checkBox.IsChecked = this.ConvertToBool(value); checkBox.Tag = key; if (Application.Current != null && Application.Current.Resources != null) { checkBox.Style = Application.Current.Resources["chkBullet"] as Style; } checkBox.Checked += CheckBox_CheckStatusChanged; checkBox.Unchecked += CheckBox_CheckStatusChanged; grid.Children.Add(checkBox); } catch (Exception ex) { Logger.GetInstance().log.Error(ex.ToString()); } } private void CreateCheckboxButton(Grid grid, string key, string value, int rowIndex) { try { CheckBox checkBoxButton = new CheckBox(); checkBoxButton.Content = LanguageResources.GetInstance().GetResource(key).ToString(); checkBoxButton.SetValue(Grid.RowProperty, rowIndex); checkBoxButton.SetValue(Grid.ColumnProperty, 2); checkBoxButton.HorizontalAlignment = HorizontalAlignment.Left; checkBoxButton.VerticalAlignment = VerticalAlignment.Center; checkBoxButton.Width = 150; checkBoxButton.Height = ConstModel.controlHeight; checkBoxButton.IsChecked = this.ConvertToBool(value); checkBoxButton.Tag = key; if (Application.Current != null && Application.Current.Resources != null) { checkBoxButton.Style = Application.Current.Resources["CommonChechBox3"] as Style; } checkBoxButton.Checked += CheckBoxButton_CheckStatusChanged; checkBoxButton.Unchecked += CheckBoxButton_CheckStatusChanged; grid.Children.Add(checkBoxButton); } catch (Exception ex) { Logger.GetInstance().log.Error(ex.ToString()); } } private void CreateNumericControl(Grid grid, string key,JToken jToken, int rowIndex,string typeValue) { try { NumericControl controlNum = new NumericControl(); controlNum.SetValue(Grid.RowProperty, rowIndex); controlNum.SetValue(Grid.ColumnProperty, 2); controlNum.HorizontalAlignment = HorizontalAlignment.Left; controlNum.VerticalAlignment = VerticalAlignment.Center; controlNum.Width = ConstModel.controlWidth; controlNum.Height = ConstModel.controlHeight; //controlNum.Margin = new Thickness(100, 0, 0, 0); if (typeValue == "int") { controlNum.MinValue = ConvertToInt(this.GetJPropertyValue(jToken, ConstModel.minKey)); controlNum.MaxValue = ConvertToInt(this.GetJPropertyValue(jToken, ConstModel.maxKey)); controlNum.Increment = 1; controlNum.Value = ConvertToInt(this.GetJPropertyValue(jToken, ConstModel.valueKey)); controlNum.ValueText.LostFocus += IntNumericTextBox_LostFocus; controlNum.ValueText.KeyDown += IntNumericTextBox_KeyDown; controlNum.ValueChanged += IntNumericValueChanged; } else { controlNum.MinValue = ConvertToFloat(this.GetJPropertyValue(jToken, ConstModel.minKey)); controlNum.MaxValue = ConvertToFloat(this.GetJPropertyValue(jToken, ConstModel.maxKey)); //每次缩进必须在赋值之前,否则float数值会显示int数值 controlNum.Increment = 0.01; controlNum.Value = ConvertToFloat(this.GetJPropertyValue(jToken, ConstModel.valueKey)); controlNum.ValueText.LostFocus += FloatNumericTextBox_LostFocus; controlNum.ValueText.KeyDown += FloatNumericTextBox_KeyDown; controlNum.ValueChanged += FloatNumericValueChanged; } controlNum.Tag = key; controlNum.ValueText.Tag = key; grid.Children.Add(controlNum); } catch (Exception ex) { Logger.GetInstance().log.Error(ex.ToString()); } } private void CreateTextBox(Grid grid, string key, JToken jToken, string text, int rowIndex) { try { TextBox textBox = new TextBox(); textBox.Text = text; textBox.Tag = key; textBox.Width = ConstModel.controlWidth; textBox.SetValue(Grid.RowProperty, rowIndex); textBox.SetValue(Grid.ColumnProperty, 2); textBox.VerticalAlignment = VerticalAlignment.Center; textBox.HorizontalAlignment = HorizontalAlignment.Left; if (Application.Current != null && Application.Current.Resources != null) { textBox.Style = Application.Current.Resources["CommonTextBoxStyle"] as Style; } if (!textBoxOldValueDic.ContainsKey(key)) { textBoxOldValueDic.Add(key, text); } //重量模块的输入字符串和标识符不让输入中文,其他地方的TextBox可以输入中文 if (key == ConstModel.inStringKey || key == ConstModel.iDentifierKey) { System.Windows.Input.InputMethod.SetIsInputMethodEnabled(textBox, false); } textBox.MaxLength = ConvertToInt(this.GetJPropertyValue(jToken, ConstModel.maxKey)); textBox.TextChanged += TextBox_TextChanged; textBox.LostFocus += TextBox_LostFocus; textBox.KeyDown += TextBox_KeyDown; grid.Children.Add(textBox); } catch (Exception ex) { Logger.GetInstance().log.Error(ex.ToString()); } } private void CreateRangeControl(Grid grid, string key, JToken jToken, int rowIndex, string typeValue) { try { RangeControl rangeControl = new RangeControl(); rangeControl.SetValue(Grid.RowProperty, rowIndex); rangeControl.SetValue(Grid.ColumnProperty, 2); rangeControl.HorizontalAlignment = HorizontalAlignment.Left; rangeControl.VerticalAlignment = VerticalAlignment.Center; rangeControl.Height = ConstModel.controlHeight; if (typeValue == "intRange") { rangeControl.LeftMinValue = ConvertToInt(this.GetJPropertyValue(jToken, ConstModel.minKey)); rangeControl.LeftMaxValue = ConvertToInt(this.GetJPropertyValue(jToken, ConstModel.maxKey)); rangeControl.RightMinValue = ConvertToInt(this.GetJPropertyValue(jToken, ConstModel.minKey)); rangeControl.RightMaxValue = ConvertToInt(this.GetJPropertyValue(jToken, ConstModel.maxKey)); rangeControl.Increment = 1; rangeControl.LeftValue = ConvertToInt(this.GetJPropertyValue(jToken, ConstModel.leftValueKey)); rangeControl.RightValue = ConvertToInt(this.GetJPropertyValue(jToken, ConstModel.rightValueKey)); rangeControl.LeftNumericControl.ValueText.LostFocus += IntRangeLeftTextBox_LostFocus; rangeControl.LeftNumericControl.ValueText.KeyDown += IntRangeLeftTextBox_KeyDown; rangeControl.LeftNumericControl.ValueChanged += IntRangeLeftValueChanged; rangeControl.RightNumericControl.ValueText.LostFocus += IntRangeRightTextBox_LostFocus; rangeControl.RightNumericControl.ValueText.KeyDown += IntRangeRightTextBox_KeyDown; rangeControl.RightNumericControl.ValueChanged += IntRangeRightValueChanged; } else { rangeControl.LeftMinValue = ConvertToFloat(this.GetJPropertyValue(jToken, ConstModel.minKey)); rangeControl.LeftMaxValue = ConvertToFloat(this.GetJPropertyValue(jToken, ConstModel.maxKey)); rangeControl.RightMinValue = ConvertToFloat(this.GetJPropertyValue(jToken, ConstModel.minKey)); rangeControl.RightMaxValue = ConvertToFloat(this.GetJPropertyValue(jToken, ConstModel.maxKey)); //每次缩进必须在赋值之前,否则float数值会显示int数值 rangeControl.Increment = 0.01; rangeControl.LeftValue = ConvertToFloat(this.GetJPropertyValue(jToken, ConstModel.leftValueKey)); rangeControl.RightValue = ConvertToFloat(this.GetJPropertyValue(jToken, ConstModel.rightValueKey)); rangeControl.LeftNumericControl.ValueText.LostFocus += FloatRangeLeftTextBox_LostFocus; rangeControl.LeftNumericControl.ValueText.KeyDown += FloatRangeLeftTextBox_KeyDown; rangeControl.LeftNumericControl.ValueChanged += FloatRangeLeftValueChanged; rangeControl.RightNumericControl.ValueText.LostFocus += FloatRangeRightTextBox_LostFocus; rangeControl.RightNumericControl.ValueText.KeyDown += FloatRangeRightTextBox_KeyDown; rangeControl.RightNumericControl.ValueChanged += FloatRangeRightValueChanged; } rangeControl.LeftNumericControl.ValueText.Tag = key; rangeControl.RightNumericControl.ValueText.Tag = key; grid.Children.Add(rangeControl); } catch (Exception ex) { Logger.GetInstance().log.Error(ex.ToString()); } } private void CreateCheckBoxsControl(Grid grid, string key, JToken jToken, int rowIndex) { try { string values = this.GetJPropertyValue(jToken, ConstModel.valuesKey); string selectValues = this.GetJPropertyValue(jToken, ConstModel.valueKey); CheckBoxsControl checkBoxsControl = new CheckBoxsControl(values, selectValues, ModuleCheckBox_CheckStatusChanged); checkBoxsControl.SetValue(Grid.RowProperty, rowIndex); checkBoxsControl.SetValue(Grid.ColumnProperty, 2); checkBoxsControl.HorizontalAlignment = HorizontalAlignment.Left; checkBoxsControl.VerticalAlignment = VerticalAlignment.Center; checkBoxsControl.Width = ConstModel.controlWidth; checkBoxsControl.Tag = key; grid.Children.Add(checkBoxsControl); } catch (Exception ex) { Logger.GetInstance().log.Error(ex.ToString()); } } private void CreateFilePathControl(Grid grid, string key, JToken jToken, int rowIndex) { try { TextBOXANDButtonUserControl filePathControl = new TextBOXANDButtonUserControl(); filePathControl.SetValue(Grid.RowProperty, rowIndex); filePathControl.SetValue(Grid.ColumnProperty, 2); filePathControl.HorizontalAlignment = HorizontalAlignment.Left; filePathControl.VerticalAlignment = VerticalAlignment.Center; filePathControl.Width = ConstModel.controlWidth; filePathControl.Height = ConstModel.controlHeight; string fileNames = this.GetJPropertyValue(jToken, "fileNames"); if (string.IsNullOrEmpty(fileNames)) { filePathControl.OpenFileType = "2"; //文件夹路径选择有最大长度限制 filePathControl.MaxLength = ConvertToInt(this.GetJPropertyValue(jToken, ConstModel.maxKey)); } else { filePathControl.OpenFileType = "3"; string[] fileNameArray = fileNames.Split(‘,‘); foreach (string fileName in fileNameArray) { filePathControl.FileFilter = string.Format("{0}{1}", filePathControl.FileFilter, string.Format("{0}|{1}", fileName, fileName)); } } filePathControl.ValueText.Tag = key; filePathControl.Value = this.GetJPropertyValue(jToken, ConstModel.valueKey); filePathControl.ValueChanged += FilePathControlValueChanged; grid.Children.Add(filePathControl); } catch (Exception ex) { Logger.GetInstance().log.Error(ex.ToString()); } } #endregion
#region 控件事件
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { //根据对象的tag标签找到currentJObject中对应的节点,对节点修改再序列化调用Set方法 ComboBox comboBox = sender as ComboBox; if (comboBox != null) { object tag = comboBox.Tag; if (tag != null) { string jPropertyName = tag.ToString(); if (comboBox.SelectedItem != null) { ComboBoxItem comboBoxItem = comboBox.SelectedItem as ComboBoxItem; if (comboBoxItem != null && comboBoxItem.Content != null) { //中文转英文字段处理 string value = comboBoxItem.Content.ToString(); string enValue = string.Empty; if (enzhDic.TryGetValue(value, out enValue)) { value = enValue; } string strCurrentJObject = this.GetCurrentJObjectStr(jPropertyName, value, ConstModel.valueKey); if (this.SetConfig(strCurrentJObject)) { this.ReloadControls(); } } } } } } private void CheckBox_CheckStatusChanged(object sender, RoutedEventArgs e) { CheckBox cb = sender as CheckBox; if (cb != null && cb.Tag != null) { string jPropertyName = cb.Tag.ToString(); bool value = (bool)cb.IsChecked; string strCurrentJObject = this.GetCurrentJObjectStr(jPropertyName, value, ConstModel.valueKey); if (this.SetConfig(strCurrentJObject)) { if (this.ReloadAutoLayoutPage != null) { if (jPropertyName == ConstModel.weightModuleEnable || jPropertyName == ConstModel.FixedWeightEnable || jPropertyName == ConstModel.plcWeightEnable) { this.ReloadAutoLayoutPage(); } else { this.ReloadControls(); } } else { this.ReloadControls(); } } } }
private void CheckBoxButton_CheckStatusChanged(object sender, RoutedEventArgs e) { CheckBox cb = sender as CheckBox; if (cb != null && cb.Tag != null) { string jPropertyName = cb.Tag.ToString(); bool value = (bool)cb.IsChecked; string strCurrentJObject = this.GetCurrentJObjectStr(jPropertyName, value, ConstModel.valueKey); if (this.SetConfig(strCurrentJObject)) { if (this.ReloadAutoLayoutPage != null) { if (jPropertyName == ConstModel.weightModuleEnable || jPropertyName == ConstModel.FixedWeightEnable || jPropertyName == ConstModel.plcWeightEnable) { this.ReloadAutoLayoutPage(); } else { this.ReloadControls(); } } else { this.ReloadControls(); } } } } private void ModuleCheckBox_CheckStatusChanged(string jPropertyName, string value) { string strCurrentJObject = this.GetCurrentJObjectStr(jPropertyName, value, ConstModel.valueKey); if (!this.SetConfig(strCurrentJObject)) { //Box框周围变红 } } private void TextBox_TextChanged(object sender, TextChangedEventArgs e) { TextBox tb = sender as TextBox;
if (tb != null && tb.Tag != null) { if (textBoxOldValueDic.ContainsKey(tb.Tag.ToString())) { if (!string.IsNullOrEmpty(tb.Text)) { textBoxOldValueDic[tb.Tag.ToString()] = tb.Text; } } } } private void TextBox_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { SendTextBoxValue(sender); } } private void TextBox_LostFocus(object sender, RoutedEventArgs e) { TextBox tb = sender as TextBox; if (tb != null) { if (string.IsNullOrEmpty(tb.Text)) { string text = string.Empty; if (tb.Tag != null) { if (textBoxOldValueDic.TryGetValue(tb.Tag.ToString(), out text)) { tb.Text = text; tb.SelectionStart = tb.Text.Length; } } } } SendTextBoxValue(sender); } private void SendTextBoxValue(object sender) { TextBox textBox = (sender as TextBox); if (textBox != null) { if (textBox.Tag != null) { string jPropertyName = textBox.Tag.ToString(); string old = GetTextBoxOldValue(jPropertyName, ConstModel.valueKey); string value = (sender as TextBox).Text; if (old == value) { return; } string strCurrentJObject = this.GetCurrentJObjectStr(jPropertyName, value, ConstModel.valueKey); if (!this.SetConfig(strCurrentJObject)) { //Box框周围变红 //textBox.BorderThickness = new Thickness(0); } } } } private void IntNumericTextBox_LostFocus(object sender, RoutedEventArgs e) { SetIntNumericTextBoxValue(sender, ConstModel.valueKey); } private void IntNumericTextBox_KeyDown(object sender, KeyEventArgs e) { if(e.Key== Key.Enter) { SetIntNumericTextBoxValue(sender, ConstModel.valueKey); } } private void FloatNumericTextBox_LostFocus(object sender, RoutedEventArgs e) { SendFloatNumericTextBoxValue(sender, ConstModel.valueKey); } private void FloatNumericTextBox_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { SendFloatNumericTextBoxValue(sender, ConstModel.valueKey); } } private void IntNumericValueChanged(object sender) { SetIntNumericTextBoxValue(sender, ConstModel.valueKey); } private void FloatNumericValueChanged(object sender) { SendFloatNumericTextBoxValue(sender, ConstModel.valueKey); } private void FilePathControlValueChanged(object sender) { TextBox tb = sender as TextBox; if (tb != null && tb.Tag != null) { this.SendFilePathControlValue(tb.Tag.ToString(), tb.Text, ConstModel.valueKey); } }
#region Range控件Textbox事件 private void IntRangeLeftTextBox_LostFocus(object sender, RoutedEventArgs e) { SetIntNumericTextBoxValue(sender, ConstModel.leftValueKey); } private void IntRangeLeftTextBox_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { SetIntNumericTextBoxValue(sender, ConstModel.leftValueKey); } } private void IntRangeRightTextBox_LostFocus(object sender, RoutedEventArgs e) { SetIntNumericTextBoxValue(sender, ConstModel.rightValueKey); } private void IntRangeRightTextBox_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { SetIntNumericTextBoxValue(sender, ConstModel.rightValueKey); } } private void FloatRangeLeftTextBox_LostFocus(object sender, RoutedEventArgs e) { SendFloatNumericTextBoxValue(sender, ConstModel.leftValueKey); } private void FloatRangeLeftTextBox_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { SendFloatNumericTextBoxValue(sender, ConstModel.leftValueKey); } } private void FloatRangeRightTextBox_LostFocus(object sender, RoutedEventArgs e) { SendFloatNumericTextBoxValue(sender, ConstModel.rightValueKey); } private void FloatRangeRightTextBox_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { SendFloatNumericTextBoxValue(sender, ConstModel.rightValueKey); } } private void IntRangeLeftValueChanged(object sender) { SetIntNumericTextBoxValue(sender, ConstModel.leftValueKey); } private void IntRangeRightValueChanged(object sender) { SetIntNumericTextBoxValue(sender, ConstModel.rightValueKey); } private void FloatRangeLeftValueChanged(object sender) { SendFloatNumericTextBoxValue(sender, ConstModel.leftValueKey); } private void FloatRangeRightValueChanged(object sender) { SendFloatNumericTextBoxValue(sender, ConstModel.rightValueKey); } #endregion
#endregion }}
原文:https://www.cnblogs.com/EasonKing/p/14362880.html