如果你的内容是静态的,你可以简单地定义你的按钮,像这样:
<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;
}
}
}
酷!我会试试这个!非常感谢! – spspli
让我知道是否有任何错误。我从我使用的代码中做了一些更改,但没有测试它编译的代码。 – Pakman
你有没有尝试过斜体值部分更花哨的风格?你知道我可以运用任何我喜欢这个价值的风格吗?或者只是像字体等简单的风格? DefaultContent。替换(值,“”+ value +“ ”) –
spspli