在WPF中创建吉他和弦编辑器(来自RichTextBox?)

Ras*_*sto 19 .net wpf user-interface richtextbox music-notation

我正在WPF工作的主要目的是允许编辑并因此在其上打印带有吉他和弦的歌曲歌词.

即使你不玩任何乐器,你可能已经看过和弦.为了给你一个想法,它看起来像这样:

E                 E6
I know I stand in line until you
E                  E6               F#m            B F#m B
think you have the time to spend an evening with me
Run Code Online (Sandbox Code Playgroud)

但是我不想使用这种丑陋的单行间距字体,而是希望Times New Roman字体与歌词和和弦(粗体字的和弦)进行字距调整.我希望用户能够编辑它.

这似乎不是支持的方案RichTextBox.这些是我不知道如何解决的一些问题:

  • 和弦的位置固定在歌词文本中的某些字符上(或更常见的TextPointer是歌词行).当用户编辑歌词时,我希望和弦保持在正确的角色上.例:

.

E                                       E6
I know !!!SOME TEXT REPLACED HERE!!! in line until you
Run Code Online (Sandbox Code Playgroud)
  • 换行:2行(带和弦的第1行和带歌词的第2行)在包装时逻辑上是一行.当一个单词换行到下一行时,它上面的所有和弦也应该换行.此外,当和弦包裹它已经结束的词时,它也会包裹.例:

.

E                  E6
think you have the time to spend an
F#m            B F#m B
evening with me
Run Code Online (Sandbox Code Playgroud)
  • 即使和弦彼此太近,和弦也应保持正确的特征.在这种情况下,一些额外的空间会自动插入歌词行中.例:

.

                  F#m E6
  ...you have the ti  me to spend... 
Run Code Online (Sandbox Code Playgroud)
  • 说我有歌词Ta VA和和弦A.我希望歌词看起来像kering对了 不喜欢 在此输入图像描述.第二张图片之间V并没有A.橙色线条仅用于显示效果(但它们标记了将放置和弦的x偏移).用于生成第一个样本的代码是<TextBlock FontFamily="Times New Roman" FontSize="60">Ta VA</TextBlock>第二个样本<TextBlock FontFamily="Times New Roman" FontSize="60"><Span>Ta V<Floater />A</Span></TextBlock>.

关于如何RichTextBox做到这一点的任何想法?或者在WPF中有更好的方法吗?我会分类Inline还是Run帮助?欢迎任何想法,黑客,TextPointer魔术,代码或相关主题的链接.


编辑:

我正在探索解决这个问题的两个主要方向,但两者都会导致另一个问题,所以我问了一个新问题:

  1. 试着RichTextBox变成和弦编辑器 - 看看如何创建类Inline的子类?.
  2. HB答案中所建议的,从Panels TextBoxes等单独的组件构建新的编辑器.这需要大量编码,并导致以下(未解决)问题:


编辑#2

MarkusHütter的高质量答案告诉我,RichTextBox当我试图根据自己的需要调整它时,我可以做更多的事情.我现在有时间详细探讨答案.马库斯可能是RichTextBox魔术师我需要帮助我,但他的解决方案也有一些未解决的问题:

  1. 这个应用程序将是关于"精美"打印的歌词.主要目标是从印刷的角度看文本看起来很完美.当和弦彼此太靠近或甚至重叠时,Markus建议我在其位置之前迭代地添加额外空间,直到它们的距离足够.实际上要求用户可以设置2个和弦之间的最小距离.应该尊重该最小距离,并且必要时不超过该距离.空间不够精细 - 一旦我添加了所需的最后空间,我可能会使间隙变宽,然后必要 - 这将使文档看起来"不好"我不认为它可以被接受.我需要插入自定义宽度的空间.
  2. 可能有没有和弦的线条(只有文字)或甚至没有文字的线条(只有和弦).当为整个文档LineHeight设置为25或其他固定值时,将导致没有和弦的行在其上方具有"空行".当只有和弦而没有文字时,它们就没有空间.

还有其他一些小问题,但我想我可以解决它们,或者我认为它们不重要.无论如何,我认为马库斯的回答非常有价值 - 不仅是为了向我展示可行的方式,而且还展示了RichTextBox与装饰师一起使用的一般模式.

H.B*_*.B. 16

我不能给你任何具体的帮助,但在建筑方面你需要改变你的布局

线吮吸

对此

字形规则

其他一切都是黑客.你的单位/字形必须成为单词和弦对.


编辑:我一直在使用模板化的ItemsControl,它甚至可以在某种程度上工作,所以它可能是有趣的.

<ItemsControl Grid.IsSharedSizeScope="True" ItemsSource="{Binding SheetData}"
              Name="_chordEditor">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition SharedSizeGroup="A" Height="Auto"/>
                    <RowDefinition SharedSizeGroup="B" Height="Auto"/>
                </Grid.RowDefinitions>
                <Grid.Children>
                    <TextBox Name="chordTB" Grid.Row="0" Text="{Binding Chord}"/>
                    <TextBox Name="wordTB"  Grid.Row="1" Text="{Binding Word}"
                             PreviewKeyDown="Glyph_Word_KeyDown" TextChanged="Glyph_Word_TextChanged"/>
                </Grid.Children>
            </Grid>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
Run Code Online (Sandbox Code Playgroud)
private readonly ObservableCollection<ChordWordPair> _sheetData = new ObservableCollection<ChordWordPair>();
public ObservableCollection<ChordWordPair> SheetData
{
    get { return _sheetData; }
}
Run Code Online (Sandbox Code Playgroud)
public class ChordWordPair: INotifyPropertyChanged
{
    private string _chord = String.Empty;
    public string Chord
    {
        get { return _chord; }
        set
        {
            if (_chord != value)
            {
                _chord = value;
                // This uses some reflection extension method,
                // a normal event raising method would do just fine.
                PropertyChanged.Notify(() => this.Chord);
            }
        }
    }

    private string _word = String.Empty;
    public string Word
    {
        get { return _word; }
        set
        {
            if (_word != value)
            {
                _word = value;
                PropertyChanged.Notify(() => this.Word);
            }
        }
    }

    public ChordWordPair() { }
    public ChordWordPair(string word, string chord)
    {
        Word = word;
        Chord = chord;
    }

    public event PropertyChangedEventHandler PropertyChanged;
}
Run Code Online (Sandbox Code Playgroud)
private void AddNewGlyph(string text, int index)
{
    var glyph = new ChordWordPair(text, String.Empty);
    SheetData.Insert(index, glyph);
    FocusGlyphTextBox(glyph, false);
}

private void FocusGlyphTextBox(ChordWordPair glyph, bool moveCaretToEnd)
{
    var cp = _chordEditor.ItemContainerGenerator.ContainerFromItem(glyph) as ContentPresenter;
    Action focusAction = () =>
    {
        var grid = VisualTreeHelper.GetChild(cp, 0) as Grid;
        var wordTB = grid.Children[1] as TextBox;
        Keyboard.Focus(wordTB);
        if (moveCaretToEnd)
        {
            wordTB.CaretIndex = int.MaxValue;
        }
    };
    if (!cp.IsLoaded)
    {
        cp.Loaded += (s, e) => focusAction.Invoke();
    }
    else
    {
        focusAction.Invoke();
    }
}

private void Glyph_Word_TextChanged(object sender, TextChangedEventArgs e)
{
    var glyph = (sender as FrameworkElement).DataContext as ChordWordPair;
    var tb = sender as TextBox;

    string[] glyphs = tb.Text.Split(' ');
    if (glyphs.Length > 1)
    {
        glyph.Word = glyphs[0];
        for (int i = 1; i < glyphs.Length; i++)
        {
            AddNewGlyph(glyphs[i], SheetData.IndexOf(glyph) + i);
        }
    }
}

private void Glyph_Word_KeyDown(object sender, KeyEventArgs e)
{
    var tb = sender as TextBox;
    var glyph = (sender as FrameworkElement).DataContext as ChordWordPair;

    if (e.Key == Key.Left && tb.CaretIndex == 0 || e.Key == Key.Back && tb.Text == String.Empty)
    {
        int i = SheetData.IndexOf(glyph);
        if (i > 0)
        {
            var leftGlyph = SheetData[i - 1];
            FocusGlyphTextBox(leftGlyph, true);
            e.Handled = true;
            if (e.Key == Key.Back) SheetData.Remove(glyph);
        }
    }
    if (e.Key == Key.Right && tb.CaretIndex == tb.Text.Length)
    {
        int i = SheetData.IndexOf(glyph);
        if (i < SheetData.Count - 1)
        {
            var rightGlyph = SheetData[i + 1];
            FocusGlyphTextBox(rightGlyph, false);
            e.Handled = true;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

最初应该将一些字形添加到集合中,否则将不会有输入字段(这可以通过进一步模板化来避免,例如,如果集合为空,则使用显示字段的数据触发器).

完善这一点需要进行大量额外的工作,例如TextBoxes的样式,添加书写换行符(现在它只在换行盘制作时断开),支持多个文本框中的选择等.


Mar*_*ter 12

Soooo,我在这里玩得很开心.这是它的样子:

捕获

歌词是完全可编辑的,和弦目前不是(但这将是一个简单的扩展).

这是xaml:

<Window ...>
    <AdornerDecorator>
        <!-- setting the LineHeight enables us to position the Adorner on top of the text -->
        <RichTextBox TextBlock.LineHeight="25" Padding="0,25,0,0" Name="RTB"/>
    </AdornerDecorator>    
</Window>
Run Code Online (Sandbox Code Playgroud)

这是代码:

public partial class MainWindow
{
    public MainWindow()
    {
        InitializeComponent();
        const string input = "E                 E6\nI know I stand in line until you\nE                  E6               F#m            B F#m B\nthink you have the time to spend an evening with me                ";
        var lines = input.Split('\n');

        var paragraph = new Paragraph{Margin = new Thickness(0),Padding = new Thickness(0)}; // Paragraph sets default margins, don't want those

        RTB.Document = new FlowDocument(paragraph);

        // this is getting the AdornerLayer, we explicitly included in the xaml.
        // in it's visual tree the RTB actually has an AdornerLayer, that would rather
        // be the AdornerLayer we want to get
        // for that you will either want to subclass RichTextBox to expose the Child of
        // GetTemplateChild("ContentElement") (which supposedly is the ScrollViewer
        // that hosts the FlowDocument as of http://msdn.microsoft.com/en-us/library/ff457769(v=vs.95).aspx 
        // , I hope this holds true for WPF as well, I rather remember this being something
        // called "PART_ScrollSomething", but I'm sure you will find that out)
        //
        // another option would be to not subclass from RTB and just traverse the VisualTree
        // with the VisualTreeHelper to find the UIElement that you can use for GetAdornerLayer
        var adornerLayer = AdornerLayer.GetAdornerLayer(RTB);

        for (var i = 1; i < lines.Length; i += 2)
        {
            var run = new Run(lines[i]);
            paragraph.Inlines.Add(run);
            paragraph.Inlines.Add(new LineBreak());

            var chordpos = lines[i - 1].Split(' ');
            var pos = 0;
            foreach (string t in chordpos)
            {
                if (!string.IsNullOrEmpty(t))
                {
                    var position = run.ContentStart.GetPositionAtOffset(pos);
                    adornerLayer.Add(new ChordAdorner(RTB,t,position));
                }
                pos += t.Length + 1;
            }
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

使用此装饰:

public class ChordAdorner : Adorner
{
    private readonly TextPointer _position;

    private static readonly PropertyInfo TextViewProperty = typeof(TextSelection).GetProperty("TextView", BindingFlags.Instance | BindingFlags.NonPublic);
    private static readonly EventInfo TextViewUpdateEvent = TextViewProperty.PropertyType.GetEvent("Updated");

    private readonly FormattedText _formattedText;

    public ChordAdorner(RichTextBox adornedElement, string chord, TextPointer position) : base(adornedElement)
    {
        _position = position;
        // I'm in no way associated with the font used, nor recommend it, it's just the first example I found of FormattedText
        _formattedText = new FormattedText(chord, CultureInfo.GetCultureInfo("en-us"),FlowDirection.LeftToRight,new Typeface(new FontFamily("Arial").ToString()),12,Brushes.Black);

        // this is where the magic starts
        // you would otherwise not know when to actually reposition the drawn Chords
        // you could otherwise only subscribe to TextChanged and schedule a Dispatcher
        // call to update this Adorner, which either fires too often or not often enough
        // that's why you're using the RichTextBox.Selection.TextView.Updated event
        // (you're then basically updating the same time that the Caret-Adorner
        // updates it's position)
        Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(() =>
        {
            object textView = TextViewProperty.GetValue(adornedElement.Selection, null);
            TextViewUpdateEvent.AddEventHandler(textView, Delegate.CreateDelegate(TextViewUpdateEvent.EventHandlerType, ((Action<object, EventArgs>)TextViewUpdated).Target, ((Action<object, EventArgs>)TextViewUpdated).Method));
            InvalidateVisual(); //call here an event that triggers the update, if 
                                //you later decide you want to include a whole VisualTree
                                //you will have to change this as well as this ----------.
        }));                                                                          // |
    }                                                                                 // |
                                                                                      // |
    public void TextViewUpdated(object sender, EventArgs e)                           // |
    {                                                                                 // V
        Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(InvalidateVisual));
    }

    protected override void OnRender(DrawingContext drawingContext)
    {
        if(!_position.HasValidLayout) return; // with the current setup this *should* always be true. check anyway
        var pos = _position.GetCharacterRect(LogicalDirection.Forward).TopLeft;
        pos += new Vector(0, -10); //reposition so it's on top of the line
        drawingContext.DrawText(_formattedText,pos);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是使用像大卫建议的装饰,但我知道很难找到如何在那里.那可能是因为没有.我花了几个小时才在反射器中试图找到确切的事件,这个事件表明已经找到了flowdocument的布局.

我不确定是否确实需要在构造函数中调度调度程序,但是我将其保留为防弹.(我需要这个,因为在我的设置中还没有显示RichTextBox).

显然,这需要更多的编码,但这将为您提供一个开始.你会想要玩定位等.

如果两个装饰品太靠近并且重叠,那么为了获得正确的定位,我建议你以某种方式跟踪之前的装饰,并查看当前装饰是否会重叠.然后你可以在_position-TextPointer 之前迭代地插入一个空格.

如果您以后决定,您也希望和弦可以编辑,那么您可以在OnRender中绘制文本,而不是在装饰器下方拥有整个VisualTree.(是一个下面有ContentControl的装饰者的例子).请注意,您必须处理ArrangeOveride,然后通过_positionCharacterRect 正确定位Adorner .