从 WPF 中的资源文件绑定占位符 [英] Binding placeholder from resource file in WPF
问题描述
在我的资源文件中
LOCKER NO. {0} IS OPEN
我需要将资源文件绑定到一个文本框,并希望在前景为红色的palce holder中动态设置值.
I need to bind the resource file to a text box and want to dynamically set value in palce holder with foreground as red.
下面是我的代码
<TextBlock x:Name="Title" Margin="0,70,0,0"
HorizontalAlignment="Center"
VerticalAlignment="Top"
FontSize="42"
FontWeight="SemiBold"
Foreground="#888888"
>
<TextBlock.Text>
<MultiBinding StringFormat="{x:Static prop:Resources.LockerNumberIsOpen}">
<Binding Path="PrefixWithNumber"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
如何将 {0} 中的值显示为红色?
how to show a value inside {0} as red?
从背后的代码我们可以做到
From code behind we can do
Title.Text = string.Format(Properties.Resources.LockerNumberIsOpen, (this.DataContext as OpenParcelViewModel).PrefixWithNumber);
var tr = this.Find((this.DataContext as OpenParcelViewModel).PrefixWithNumber);
tr.ApplyPropertyValue(TextElement.ForegroundProperty, "#9ebb2b");
private TextRange Find(string w)
{
var si = Title.Text.IndexOf(w);
var sp = Title.ContentStart.GetPositionAtOffset(si + 1);
var ep = Title.ContentStart.GetPositionAtOffset(si + w.Length + 1);
return new TextRange(sp, ep);
}
如何在 XAML 中做到这一点
How to do it in the XAML
推荐答案
您需要使用 RichTextBox.这将允许您为块内的文本设置不同的颜色,但我不知道如何绑定它.或许可以使用某种方法以所需格式使用资源创建对象,然后将其绑定到该对象.
You need to use a richTextBox. that will allow you to set different colour for text within the block but I don't know how to bind it. Perhaps use a method to create an object with the resource in the format needed then bind it to that object.
在 RichtextBox 中设置单独的颜色 这个问题有详细说明.
In terms of setting seperate colours in a RichtextBox this question has it in detail.
这篇关于从 WPF 中的资源文件绑定占位符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!