| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Data;
- using System.Windows.Documents;
- using System.Windows.Input;
- using System.Windows.Media;
- using System.Windows.Media.Imaging;
- using System.Windows.Navigation;
- using System.Windows.Shapes;
- namespace Muchinfo.WPF.Controls
- {
- /// <summary>
- /// 按照步骤 1a 或 1b 操作,然后执行步骤 2 以在 XAML 文件中使用此自定义控件。
- ///
- /// 步骤 1a) 在当前项目中存在的 XAML 文件中使用该自定义控件。
- /// 将此 XmlNamespace 特性添加到要使用该特性的标记文件的根
- /// 元素中:
- ///
- /// xmlns:MyNamespace="clr-namespace:Muchinfo.WPF.Controls"
- ///
- ///
- /// 步骤 1b) 在其他项目中存在的 XAML 文件中使用该自定义控件。
- /// 将此 XmlNamespace 特性添加到要使用该特性的标记文件的根
- /// 元素中:
- ///
- /// xmlns:MyNamespace="clr-namespace:Muchinfo.WPF.Controls;assembly=Muchinfo.WPF.Controls"
- ///
- /// 您还需要添加一个从 XAML 文件所在的项目到此项目的项目引用,
- /// 并重新生成以避免编译错误:
- ///
- /// 在解决方案资源管理器中右击目标项目,然后依次单击
- /// “添加引用”->“项目”->[浏览查找并选择此项目]
- ///
- ///
- /// 步骤 2)
- /// 继续操作并在 XAML 文件中使用控件。
- ///
- /// <MyNamespace:Vertical/>
- ///
- /// </summary>
- [TemplatePart(Name = VerticalTextBlock.c_TextBlock, Type = typeof(TextBlock))]
- public class VerticalTextBlock : Control
- {
- public const string c_TextBlock = "TextBlock";
- static VerticalTextBlock()
- {
- DefaultStyleKeyProperty.OverrideMetadata(typeof(VerticalTextBlock), new FrameworkPropertyMetadata(typeof(VerticalTextBlock)));
- }
- public override void OnApplyTemplate()
- {
- base.OnApplyTemplate();
- _textBlock = GetTemplateChild("TextBlock") as TextBlock;
- CreateVerticalText(_text);
- }
- private string _text { get; set; }
- private TextBlock _textBlock { get; set; }
- public string Text
- {
- get { return (string)GetValue(TextProperty); }
- set { SetValue(TextProperty, value); }
- }
- public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
- "Text", typeof(string), typeof(VerticalTextBlock), new PropertyMetadata(OnTextChanged));
- private static void OnTextChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
- {
- ((VerticalTextBlock)o).OnTextChanged((string)(e.NewValue));
- }
- private void OnTextChanged(string newValue)
- {
- CreateVerticalText(newValue);
- }
- private void CreateVerticalText(string text)
- {
- _text = text;
- if (null != _textBlock)
- {
- bool first = true;
- foreach (var c in _text)
- {
- if (!first)
- {
- _textBlock.Inlines.Add(new LineBreak());
- }
- _textBlock.Inlines.Add(new Run { Text = c.ToString() });
- first = false;
- }
- }
- }
- }
- }
|