/// <summary>/// 刷新温度计上面的内容适应定义大小/// </summary>/// <exception cref="NotImplementedException"></exception>privatevoidRefreshComponet(){// 两种方式触发:尺寸变化、区间变化var h =this.MainCanvas.ActualHeight;//通过这个判断界面元素是否加载if(h ==0)return;double w =75;// 类型double stepCount = Maxmum - Minmum;// 在这个区间内多少个间隔double step = h /(Maxmum - Minmum);// 每个间隔距离this.MainCanvas.Children.Clear();for(int i =0; i <= stepCount; i++){Line line =newLine();
line.Y1 = i * step;
line.Y2 = i * step;
line.Stroke = Brushes.Black;
line.StrokeThickness =1;this.MainCanvas.Children.Add(line);if(i %10==0){
line.X1 =15;
line.X2 = w -15;// 添加文字TextBlock text =newTextBlock{
Text =(Maxmum - i).ToString(),
Width =20,
TextAlignment = TextAlignment.Center,
FontSize =9,
Margin =newThickness(0,-5,-4,0)};
Canvas.SetLeft(text, w -15);
Canvas.SetTop(text, i * step);this.MainCanvas.Children.Add(text);// 添加文字
text =newTextBlock{
Text =(Maxmum - i).ToString(),
Width =20,
TextAlignment = TextAlignment.Center,
FontSize =9,
Margin =newThickness(-4,-5,0,0)};
Canvas.SetLeft(text,0);
Canvas.SetTop(text, i * step);this.MainCanvas.Children.Add(text);}elseif(i %5==0){
line.X1 =20;
line.X2 = w -20;}else{
line.X1 =25;
line.X2 = w -25;}}}
6、定义温度控件依赖属性和回调函数
publicint Minmum
{get{return(int)GetValue(MinmumProperty);}set{SetValue(MinmumProperty,value);}}// Using a DependencyProperty as the backing store for Minmum. This enables animation, styling, binding, etc...publicstaticreadonlyDependencyProperty MinmumProperty =
DependencyProperty.Register("Minmum",typeof(int),typeof(Thermometer),newPropertyMetadata(0,newPropertyChangedCallback(OnPropertyValueChanged)));publicint Maxmum
{get{return(int)GetValue(MaxmumProperty);}set{SetValue(MaxmumProperty,value);}}// Using a DependencyProperty as the backing store for Maxmum. This enables animation, styling, binding, etc...publicstaticreadonlyDependencyProperty MaxmumProperty =
DependencyProperty.Register("Maxmum",typeof(int),typeof(Thermometer),newPropertyMetadata(100,newPropertyChangedCallback(OnPropertyValueChanged)));publicdouble Value
{get{return(double)GetValue(ValueProperty);}set{SetValue(ValueProperty,value);}}// Using a DependencyProperty as the backing store for Value. This enables animation, styling, binding, etc...publicstaticreadonlyDependencyProperty ValueProperty =
DependencyProperty.Register("Value",typeof(double),typeof(Thermometer),newPropertyMetadata(0.0,newPropertyChangedCallback(OnPropertyValueChanged)));/// <summary>/// 当属性值发生变化的时候直接更新UI内容/// </summary>/// <param name="d"></param>/// <param name="e"></param>privatestaticvoidOnPropertyValueChanged(DependencyObject d,DependencyPropertyChangedEventArgs e){(d asThermometer)?.RefreshComponet();}