[英]Reading Windows.UI.XAML.Style properties in C#
我正在嘗試將HTML字符串轉換為RichTextBlock內容。 為此,我使用內聯,並且我想使用XAML中定義的樣式設置這些內聯的樣式屬性。
我已尋找解決方案,並發現了這個問題 。 但是,此代碼將返回BindindExpressionBase
作為結果,因此我無法將其直接設置為Run屬性。 我嘗試了不同的方法,但沒有這樣做。
這是我的XAML。
<Style x:Key="RTCodeStyle" TargetType="HyperlinkButton" BasedOn="{StaticResource BaseRichTextBlockStyle}">
<Setter Property="FontFamily" Value="Courier New" />
<Setter Property="FontSize" Value="{ThemeResource TextStyleLargeFontSize}" />
<Setter Property="Foreground" Value="Gray" />
</Style>
這就是我想要實現的。
Run r = new Run();
r.FontFamily = style.GetPropertyValue(RichTextBlock.FontFamilyProperty);
r.FontSize = style.GetPropertyValue(RichTextBlock.FontSizeProperty);
r.Foreground = style.GetPropertyValue(RichTextBlock.ForegroundProperty);
此代碼導致Cannot implicitly convert type 'object' to 'Windows.UI.Xaml.Media.FontFamily'. An explicit conversion exists (are you missing a cast?)
Cannot implicitly convert type 'object' to 'Windows.UI.Xaml.Media.FontFamily'. An explicit conversion exists (are you missing a cast?)
錯誤。 嘗試將返回值RichTextBlock.FontFamilyProperty
為RichTextBlock.FontFamilyProperty
會導致'Windows.UI.Xaml.Controls.RichTextBlock.FontFamilyProperty' is a 'property' but is used like a 'type'
錯誤一樣使用。
GetPropertyValue的正文(來自答案 )是
public static class StyleExtensions
{
public static object GetPropertyValue(this Style style, DependencyProperty property)
{
var setter =style.Setters.Cast<Setter>().FirstOrDefault(s => s.Property == property);
var value = setter != null ? setter.Value : null;
if (setter == null &&style.BasedOn != null)
value = style.BasedOn.GetPropertyValue(property);
return value;
}
}
感謝您的任何幫助。
您是否不必將其實際轉換為您感興趣的元素?
r.FontFamily = (FontFamily)style.GetPropertyValue(RichTextBlock.FontFamilyProperty);
r.FontSize = (FontSize)style.GetPropertyValue(RichTextBlock.FontSizeProperty);
r.Foreground = (Brush)style.GetPropertyValue(RichTextBlock.ForegroundProperty);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.