如何在段落中应用不同的样式

本文关键字:样式 应用 段落中 | 更新日期: 2023-09-27 17:59:06

我可以对按钮的内容应用不同的样式吗?例如,我有一个搜索框,如果用户在搜索框中输入"is"并单击搜索,我可以使下面两个"is"在按钮内容中变成斜体吗?同时,我想保持剩下的部分原样,不要斜体。

<Button
    Content="This is an example of button content. This is a very long content.">
   <Button.Style>
    ???
   </Button.Style>
</Button>

应用样式后,我想要按钮内容:此是按钮内容的示例。这是一个非常长的内容。

这可能吗?

如何在段落中应用不同的样式

如果您的内容是静态的,您可以简单地定义您的按钮,如下所示:

<Button>
    <TextBlock>
         <Run Text="This"></Run>
         <Run Text="is" FontStyle="Italic"></Run>
         <Run Text="an example of button content. This"></Run>
         <Run Text="is" FontStyle="Italic"></Run>
         <Run Text="a very long content."></Run>
    </TextBlock>
</Button>

或:

<Button>
    <RichTextBox IsReadOnly="True" BorderThickness="0"> <!-- Other styles as needed -->
        <FlowDocument>
            <Paragraph>
                This
                <Italic>is</Italic> an example of button content. This
                <Italic>is</Italic> a very long content.
            </Paragraph>
        </FlowDocument>
    </RichTextBox>
</Button>

然而,对于样式是动态的情况,我会使用以下服务:

// Note: Not my code, but I can't find the original source
public static class RichTextBoxService
{
    public static string GetContent(DependencyObject obj)
    {
        return (string)obj.GetValue(ContentProperty);
    }
    public static void SetContent(DependencyObject obj, string value)
    {
        obj.SetValue(ContentProperty, value);
    }
    public static readonly DependencyProperty ContentProperty =
        DependencyProperty.RegisterAttached("Content",
        typeof(string), 
        typeof(RichTextBoxHelper),
        new FrameworkPropertyMetadata 
        {
            BindsTwoWayByDefault = true,
            PropertyChangedCallback = OnDocumentChanged,
        });
    private static void OnDocumentChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        var richTextBox = (RichTextBox)obj;
        // Parse the XAML content to a document (or use XamlReader.Parse())
        var xaml = GetContent(richTextBox);
        var doc = new FlowDocument();
        var range = new TextRange(doc.ContentStart, doc.ContentEnd);
        range.Load(new MemoryStream(Encoding.UTF8.GetBytes(xaml)), DataFormats.Xaml);
        richTextBox.Document = doc;
        // When the document changes update the source
        range.Changed += (s, args) =>
        {
            if (richTextBox.Document == doc)
            {
                MemoryStream buffer = new MemoryStream();
                range.Save(buffer, DataFormats.Xaml);
                SetContent(richTextBox, Encoding.UTF8.GetString(buffer.ToArray()));
            }
        };
    }
}

然后,你可以像这样用你的按钮:

视图:

<Window xmlns:services="clr-namespace:MyProject.Services;assembly=MyProject">
    <Button>
        <RichTextBox IsReadOnly="True" BorderThickness="0" services:RichTextBoxService.Content="{Binding ButtonContent}" />
    </Button>

视图模型:

// Note: I can't remember is Section is required or not
private const string Header = @"<Section xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""><Paragraph>";
private const string DefaultContent = "This is an example of button content. This is a very long content";
private const string Footer = "</Paragraph></Section>";
private string _search;
public string Search
{ 
    get { return _search; }
    set {
         if (Set(ref _search, value))  // using MVVMLight
         {
             // search value was updated
             this.ButtonContent = Header + DefaultContent.Replace(value, "<Italic>" + value + "</Italic>") + Footer;
         }
    }
}

Content可以是任何东西,例如,每个单词或文本段包含一个RunTextBlock,然后您可以对其进行单独的样式设置。我认为纯XAML方法在这里不是很有用。如果您想在资源中的某个地方定义突出显示样式,那么根据用户输入在代码中有条件地应用该样式。

我会简单地定义你的按钮如下:

                <Button.Content>
                <TextBlock>
                    <Run Text="This" />
                    <Run Text="is" FontStyle="{Binding Converter={StaticResource ItalicConverter}}" />
                    <Run Text="a..."  />
                </TextBlock>
            </Button.Content>

然后我会使用ValueConverter来检查用户是否按下了另一个按钮来更改样式。

类似这样的东西:

    public class ItalicConverter : IValueConverter
    {
         public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
         {
            return "Italic";
         }
         public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
         {
            return true;
         }
     }

您必须添加逻辑才能将其转换回正常