0

I've been set to maintain a wpf application where there is a listbox for logging purposes.

The items displayed using listbox are of type TextMessage, i.e. the listbox is bound to these text messages via

ObservableCollection<TextMessage> Messages; listBox.DataContext = Messages;

Messages are then added with something like

Messages.Add(new TextMessage("Test", TypeOfMessage.Headline));

This is the definition of the class TextMessage

public enum TypeOfMessage
{
    Normal,
    Headline,
    Focus,
    Important,
    Fail,
    Success
}

public class TextMessage
{
    public TextMessage(string content, TypeOfMessage typeOfMessage)
    {
        Content = content;
        TypeOfMessage = typeOfMessage;
        CreationTime = DateTime.Now;
    }

    public string Content { get; }
    public TypeOfMessage TypeOfMessage { get; }
    public DateTime CreationTime { get; }
}

The xaml definition for the listbox is something like this:

    <ListBox x:Name="listBox" HorizontalAlignment="Left" Height="196" Margin="101,77,0,0" VerticalAlignment="Top" Width="256" ItemsSource="{Binding}" SelectionMode="Multiple">


        <ListBox.InputBindings>
            <KeyBinding
                    Key="C"
                    Modifiers="Control"
                    Command="Copy"
                />
        </ListBox.InputBindings>
        <ListBox.CommandBindings>
            <CommandBinding 
                    Command="Copy"
                    Executed="DoPerformCopy"
                />
        </ListBox.CommandBindings>



        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock x:Name="TextToShow"  Text="{Binding Content}"></TextBlock>
                <DataTemplate.Triggers>
                    <DataTrigger Binding="{Binding TypeOfMessage}" Value="Normal">
                        <Setter TargetName="TextToShow" Property="Foreground" Value="Black"/>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding TypeOfMessage}" Value="Focus">
                        <Setter TargetName="TextToShow" Property="Foreground" Value="Black"/>
                        <Setter TargetName="TextToShow" Property="FontWeight" Value="Bold"/>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding TypeOfMessage}" Value="Headline">
                        <Setter TargetName="TextToShow" Property="Foreground" Value="RoyalBlue"/>
                        <Setter TargetName="TextToShow" Property="FontWeight" Value="Bold"/>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding TypeOfMessage}" Value="Important">
                        <Setter TargetName="TextToShow" Property="Foreground" Value="Red"/>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding TypeOfMessage}" Value="Fail">
                        <Setter TargetName="TextToShow" Property="Foreground" Value="Red"/>
                        <Setter TargetName="TextToShow" Property="FontWeight" Value="Bold"/>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding TypeOfMessage}" Value="Success">
                        <Setter TargetName="TextToShow" Property="Foreground" Value="Green"/>
                        <Setter TargetName="TextToShow" Property="FontWeight" Value="Bold"/>
                    </DataTrigger>
                </DataTemplate.Triggers>
            </DataTemplate>
        </ListBox.ItemTemplate>


    </ListBox>

This works nicely (i.e messages are displayed in the listbox in different font weight and color depending on their type), but now for the question :

Is there any way using BindingExpression or any other means to get the font formatting and coloring from code behind from the xaml definitions ?

The reason is that I want to just have the formatting in one place (just in the xaml as it is right now) but still be able to reuse it when I want to copy the contents (using code behind) including font formatting to the clipboard.

Example:

    private void DoPerformCopy()
    {
        RichTextBox rtb = new RichTextBox();
        foreach (TextMessage message in (listBox as ListBox)?.SelectedItems.Cast<TextMessage>().ToList())
        {
            TextPointer startPos = rtb.CaretPosition;
            rtb.AppendText(message.Content);
            rtb.Selection.Select(startPos, rtb.CaretPosition.DocumentEnd);
            //
            // Here it would be very nice to instead having multiple switch statements to get the formatting for the 
            // TypeOfMessage from the xaml file.
            SolidColorBrush scb = new SolidColorBrush(message.TypeOfMessage == TypeOfMessage.Fail ? Colors.Red);
            //

            rtb.Selection.ApplyPropertyValue(RichTextBox.ForegroundProperty, scb);
        }
        // Now copy the whole thing to the Clipboard
        rtb.Selection.Select(rtb.Document.ContentStart, rtb.Document.ContentEnd);
        rtb.Copy();
    }

Since I'm new to wpf, I'd really appreciate if someone has a tip for solving this. (I've tried hard to find an solution here at stackoverflow, but so far I've been unsuccessful)

Thanks in advance,

King regards Magnus

Metscore
  • 33
  • 1
  • 3
  • Ah... Just noted that one solution would be to venture down the path of `listBox.ItemTemplate.Triggers` – Metscore Aug 25 '16 at 09:43

1 Answers1

0

Make a ContentPresenter with Content set to your TextMessage. Set the ContentTemplate to listBox.ItemTemplate and apply the template. It will create the visuals (TextBlock in this case). Then, just parse off the values from the TextBlock.

Also, your RichTextBox selection code wasn't working quite right so I fixed that by just inserting TextRanges to the end of it instead of trying to get the selection right.

private void DoPerformCopy(object sender, EventArgs e)
{
    RichTextBox rtb = new RichTextBox();
    foreach (TextMessage message in (listBox as ListBox)?.SelectedItems.Cast<TextMessage>().ToList())
    {
        ContentPresenter cp = new ContentPresenter();
        cp.Content = message;
        cp.ContentTemplate = listBox.ItemTemplate;
        cp.ApplyTemplate();
        var tb = VisualTreeHelper.GetChild(cp, 0) as TextBlock;
        var fg = tb.Foreground;
        var fw = tb.FontWeight;

        var tr = new TextRange(rtb.Document.ContentEnd, rtb.Document.ContentEnd);
        tr.Text = message.Content;
        tr.ApplyPropertyValue(RichTextBox.ForegroundProperty, fg);
        tr.ApplyPropertyValue(RichTextBox.FontWeightProperty, fw);
    }
    // Now copy the whole thing to the Clipboard
    rtb.Selection.Select(rtb.Document.ContentStart, rtb.Document.ContentEnd);
    rtb.Copy();
}
J.H.
  • 4,232
  • 1
  • 18
  • 16
  • I should've mentioned that I got the RichTextBox code from http://stackoverflow.com/questions/5512921/wpf-richtextbox-appending-coloured-text – J.H. Aug 25 '16 at 14:39