字符串转时间

var dateTime = DateTime.ParseExact("2020/1/4 16:54", "yyyy/M/d HH:mm", null);
var strDate = dateTime.ToString("yyyy-MM-dd HH:mm:ss");

string strFormat = "yyyy/M/d HH:mm";
skip_retryFormat:
string strDate = "";
try
{
var dateTime = DateTime.ParseExact(colsStr[0], strFormat, null);
strDate = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
}
catch(System.FormatException ex)
{
if (strFormat != "yyyy/M/d HH:mm:ss")
{
strFormat = "yyyy/M/d HH:mm:ss";
goto skip_retryFormat;
}else
{
MessageBox.Show("数据日期格式不支持,请联系技术支持");
}

}
阅读全文 »

public T List_obj<T>(T obj)
{
T result = default(T);
if (obj is T)
{
result = (T)(object)obj; //或 (T)((object)model);
}
return result;
}

<DockPanel>
<Menu DockPanel.Dock="Top">
<MenuItem Header="_Tools">
<MenuItem Header="_Driver" />
<MenuItem Name="menu_programe" Header="_Programe" Click="menu_programe_Click"/>
<MenuItem Header="_Measure" />
<Separator />
<MenuItem Name="menu_exit" Header="_Exit" Click="menu_exit_Click"/>
</MenuItem>
</Menu>
<Grid x:Name="grid_main" Margin="0,5,5,5" />
</DockPanel>

private void menu_programe_Click(object sender, RoutedEventArgs e)
{
grid_main.Children.Clear();
grid_main.Children.Add(new UCProgram());
}

private void menu_exit_Click(object sender, RoutedEventArgs e)
{
Close();
}

响应点击事件

private void chk_isEnable_Click(object sender, RoutedEventArgs e)
{
// 获取当前选中行,更新
var result = (sender as CheckBox).IsChecked;
}

binding

DataContext = App.db.m_config[0];

<CheckBox x:Name="chk_autoStart" IsChecked="{Binding Path=AutoStart, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" Margin="4,0">程序自启动</CheckBox>

只读

// IsHitTestVisible="False" Focusable="False" 就可以了
<CheckBox IsChecked="{Binding Path=IsValid}" IsHitTestVisible="False" Focusable="False" />

代码判断属性

if ((bool)check_clear_coder.IsChecked)
{

}

// xaml 设置好显示空间
<Grid x:Name="grid_main" Grid.Row="1" Grid.Column="2" Margin="0,5,5,5" >
</Grid>

// c# code 通过 grid_main.Children 完成页码的切换 启用
switch (item.data)
{
case (int)TREE_ITEM_INDEX.Solution:
break;
case (int)TREE_ITEM_INDEX.Sensor:
grid_main.Children.Clear();
grid_main.Children.Add(new UCSensor());
break;
case (int)TREE_ITEM_INDEX.Standard:
break;
case (int)TREE_ITEM_INDEX.measure_programe:
break;
case (int)TREE_ITEM_INDEX.coeff:
grid_main.Children.Clear();
grid_main.Children.Add(new UCCoeff());
break;
case (int)TREE_ITEM_INDEX.measure_step:
break;
case (int)TREE_ITEM_INDEX.zero_step:
break;
case (int)TREE_ITEM_INDEX.preelaboration:
break;
case (int)TREE_ITEM_INDEX.measure:
break;
default:
Log.Warning("tree index not found: " + item.data.ToString());
break;
}

Without specifying public the class is implicitly internal. This means that the class is only visible inside the same assembly. When you specify public, the class is visible outside the assembly.

It is also allowed to specify the internal modifier explicitly:

internal class Foo {}

to string

Log.Information(JsonConvert.SerializeObject(item));

copy

msdn

public class IdInfo
{
public int IdNumber;

public IdInfo(int IdNumber)
{
this.IdNumber = IdNumber;
}
}
public class Person
{
public int Age;
public string Name;
public IdInfo IdInfo;

public Person ShallowCopy()
{
return (Person) this.MemberwiseClone();
}

public Person DeepCopy()
{
Person other = (Person) this.MemberwiseClone();
other.IdInfo = new IdInfo(IdInfo.IdNumber);
other.Name = String.Copy(Name);
return other;
}
}

// Create an instance of Person and assign values to its fields.
Person p1 = new Person();
p1.Age = 42;
p1.Name = "Sam";
p1.IdInfo = new IdInfo(6565);

// Perform a shallow copy of p1 and assign it to p2.
Person p2 = p1.ShallowCopy();

SelectionChanged

private void cmb_history_type_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string str = ((sender as ComboBox).SelectedItem as ComboBoxItem).Content as string;

...
}
string str = (cmb_filter_subject.SelectedItem as ComboBoxItem).Content as string;

获取当前文字

string str = (cmb_filter_state.SelectedValue as ComboBoxItem).Content.ToString();
阅读全文 »

修饰符

$ before string

// $ is short-hand for String.Format and is used with string interpolations,
// which is a new feature of C# 6. As used in your case, it does nothing, just as string.Format() would do nothing.

var anInt = 1;
var aBool = true;
var aString = "3";
var aFloat = 12.3456
var formated = string.Format("{0},{1},{2}", anInt, aBool, aString);

// same result
var formated = $"{anInt},{aBool},{aString},{aFloat:f2}";
aFloat = 12.34

// 16进制转换
tb_test.Text = $"{it1:X}";

阅读全文 »

单行输入

<Window x:Class="WpfTutorialSamples.Basic_controls.TextBoxSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TextBoxSample" Height="80" Width="250">
<StackPanel Margin="10">
<TextBox />
</StackPanel>
</Window>

多行输入

<Window x:Class="WpfTutorialSamples.Basic_controls.TextBoxSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TextBoxSample" Height="160" Width="280">
<Grid Margin="10">
<TextBox AcceptsReturn="True" TextWrapping="Wrap" VerticalScrollBarVisibility="Visible"/>
</Grid>
</Window>

自动换行

Textwrapping = "Wrap"

追加文本

// do work
textBox.AppendText("Work finished\r\n"); // better way than Text += according to msdn
// do more
textBox.AppendText("One more message\r\n");

自动滚动到底部

tb_out.ScrollToEnd();

// 如果有问题就使用这种方式
Status.Focus();
Status.CaretIndex = Status.Text.Length;
Status.ScrollToEnd();

设置焦点

<Grid FocusManager.FocusedElement="{Binding ElementName=inputbox}">
<TextBox Name="inputbox" HorizontalAlignment="Left" Height="24" Margin="10,10,0,0"
Text="{Binding SearchText, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
TextWrapping="Wrap" VerticalAlignment="Top" Width="161">
<TextBox.InputBindings>
<!--键盘事件绑定-->
<KeyBinding Command="{Binding Search_Click}" Key="Enter"/>
</TextBox.InputBindings>
</TextBox>
</Grid>

代码实现

// 设置 扫描输入框焦点
tb_machineId.Focus();

数据绑定

<TextBox x:Name="tb_info_block_width" Grid.Column="1" Margin="2" Text="{Binding Path=Info_block_width, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBox>

tb_info_block_width.DataContext = App.db.m_config[0];

public class dbHelper:INotifyPropertyChanged
{
public ObservableCollection<Model_config> m_config = new ObservableCollection<Model_config>();

public event PropertyChangedEventHandler PropertyChanged;

public void RaisePropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}

public ObservableCollection<Model_config> List_config()
{
Log.Information("List_config enter");
m_config.Clear();
try
{
var ret = App.conn.GetTableInfo("Model_config");
if (0 == ret.Count)
{
App.conn.CreateTable<Model_config>();
}
// 访问数据库
var query = App.conn.Table<Model_config>();
foreach (var item in query)
{
m_config.Add(item);
}
return m_config;
}
catch (Exception ex)
{
MessageBox.Show("获取配置数据出现异常." + ex.Message);
Log.Error(ex, "List_config failed");
}
return m_config;
}

public int Insert_model<T>(T model)
{
try
{
// 访问数据库
var modified = App.conn.Insert(model);

return modified;
}
catch (Exception ex)
{
MessageBox.Show("插入数据出现异常." + ex.Message);
Log.Error(ex, model.ToString() + " failed");
}
return 0;
}

public int Update_model<T>(T model)
{
try
{
// 访问数据库
var modified = App.conn.Update(model);
return modified;
}
catch (Exception ex)
{
MessageBox.Show("更新数据出现异常." + ex.Message);
Log.Error(ex, model.ToString() + " failed");
}
return 0;
}

public int Delete_model<T>(T x, int id)
{
try
{
// 访问数据库
var modified = App.conn.Delete<T>(id);
return modified;
}
catch (Exception ex)
{
MessageBox.Show("删除数据出现异常." + ex.Message);
Log.Error(ex, x.ToString() + " failed");
}
return 0;
}


}

批量设置字体

<StackPanel.Resources>
<Style TargetType="TextBlock">
<Setter Property="FontSize" Value="16"/>
</Style>
<Style TargetType="TextBox">
<Setter Property="FontSize" Value="16"/>
</Style>
</StackPanel.Resources>

字体颜色

measurDisplay.tb_operate_status.Foreground = new BrushConverter().ConvertFromString("#CC0033") as SolidColorBrush;

启动时设置焦点

使用 FocusManager

<Grid FocusManager.FocusedElement="{Binding ElementName=tb_userName}">

<Window x:Class="SPCAssist.WinUserLogin"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:SPCAssist"
mc:Ignorable="d" WindowStartupLocation="CenterScreen"
Title="登录窗口" Height="200" Width="300">
<Grid FocusManager.FocusedElement="{Binding ElementName=tb_userName}">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="7*"/>
</Grid.ColumnDefinitions>
<Grid.Resources>
<Style TargetType="TextBlock">
<Setter Property="FontSize" Value="16"/>
</Style>
<Style TargetType="TextBox">
<Setter Property="FontSize" Value="16"/>
</Style>
</Grid.Resources>
<TextBlock Grid.Row="0" Grid.Column="0" Margin="10">用户名:</TextBlock>
<TextBox x:Name="tb_userName" Grid.Row="0" Grid.Column="1" Margin="10"></TextBox>
<TextBlock Grid.Row="1" Grid.Column="0" Margin="10,0">密码:</TextBlock>
<PasswordBox x:Name="tb_password" Grid.Row="1" Grid.Column="1" Margin="10,0"/>
<Button Grid.Row="2" Grid.ColumnSpan="2" Margin="10,10,10,0" Name="btnLogin" FontSize="16" Click="btnLogin_Click">登 录</Button>
</Grid>
</Window>

Label and TextBlock

Label is ContentControl which means that you can set anything as a content for it. Absolutely anything including strings, numbers, dates, other controls, images, shapes, etc. TextBlock can handle only strings.

TextBlock is not a control
Even though TextBlock lives in the System.Windows.Controls namespace, it is not a control. It derives directly from FrameworkElement. Label, on the other hand, derives from ContentControl. This means that Label can:

  • Be given a custom control template (via the Template property).
  • Display data other than just a string (via the Content property).
  • Apply a DataTemplate to its content (via the ContentTemplate property).
  • Do whatever else a ContentControl can do that a FrameworkElement cannot.

Label text is grayed out when disabled
Label supports access keys
Label is much heavier than TextBlock