注:
這個答案是基於的answer provided by mm8
的評論您可以使用轉換器將字符串轉換到SolidColorBrush
:
Converter類:
public class TextToSolidColorBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var color = Brushes.Black;
try
{
var converted = new BrushConverter().ConvertFromString(value?.ToString());
color = converted != null ? (SolidColorBrush) converted : Brushes.Black;
}
catch (Exception e)
{
// ignored
}
return color;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
XAML:
<Window.Resources>
<local:TextToSolidColorBrushConverter x:Key="TextToSolidColorBrushConverter"/>
</Window.Resources>
<TextBlock Text="Any text">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Foreground" Value="{Binding Text,RelativeSource={RelativeSource Self}, Converter={StaticResource TextToSolidColorBrushConverter}}" />
</Style>
</TextBlock.Style>
</TextBlock>
謝謝你,但文本值不是恆定的也可以是變化的。可能是顏色代碼會有所不同。我想要如包含()類型的東西 –
你在說什麼?包含? XAML中沒有這樣的事情。這與你原來的問題有什麼關係? – mm8
你有任何其他解決方案可以幫助我完成嗎? –