从Datatemplate触发器的代码中获取绑定表达式

时间:2016-08-25 09:29:52

标签: c# wpf xaml listbox binding-expressions

我已经准备好维护一个wpf应用程序,其中有一个用于记录目的的列表框。

使用列表框显示的项目属于TextMessage类型,即列表框通过

绑定到这些文本消息

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

然后添加类似

的消息

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

这是类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; }
}

列表框的xaml定义是这样的:

    <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>

这很好用(即消息在列表框中以不同的字体粗细和颜色显示,具体取决于它们的类型),但现在问题是:

有没有办法使用BindingExpression或任何其他方法从xaml定义中获取代码背后的字体格式和着色?

原因是我想在一个地方(就像现在一样在xaml中)进行格式化,但是当我想要复制内容(使用代码隐藏),包括字体格式时,仍然能够重用它到剪贴板。

示例:

    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();
    }

由于我是wpf的新手,如果有人有解决这个问题的小费,我真的很感激。 (我已经努力在stackoverflow找到解决方案,但到目前为止我一直没有成功)

提前致谢,

尊敬的 马格努斯

1 个答案:

答案 0 :(得分:0)

制作ContentPresenter,将内容设置为TextMessage。将ContentTemplate设置为listBox.ItemTemplate并应用模板。它将创建视觉效果(在本例中为TextBlock)。然后,只需解析TextBlock中的值。

此外,您的RichTextBox选择代码工作不正常所以我通过将TextRanges插入到它的末尾而不是尝试正确选择来修复它。

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();
}