WPF 텍스트를 텍스트 블록으로 설정합니다
-
16-09-2019 - |
문제
나는 그것을 알고있다 TextBlock
a FlowDocument
, 예를 들어:
<TextBlock Name="txtFont">
<Run Foreground="Maroon" FontFamily="Courier New" FontSize="24">Courier New 24</Run>
</TextBlock>
a를 설정하는 방법을 알고 싶습니다 FlowDocument
그것은 변수로 저장됩니다 TextBlock
. 나는 다음과 같은 것을 찾고 있습니다.
string text = "<Run Foreground="Maroon" FontFamily="Courier New" FontSize="24">Courier New 24</Run>"
txtFont.Text = text;
그러나 위의 코드의 결과는 XAML 텍스트가 비교할 수 없다는 것입니다.
편집하다: 내 질문이 충분히 명확하지 않은 것 같아요. 내가 정말로 달성하려는 것은 다음과 같습니다.
- 사용자는 텍스트를 a에 입력합니다 RichTextBox.
- 응용 프로그램은 사용자 입력을 AS로 저장합니다
FlowDocument
~로부터 RichTextBox, 디스크에 직렬화합니다. - 그만큼
FlowDocument
디스크에서 변수로 사형화됩니다 텍스트. - 이제 사용자 텍스트를
TextBlock
.
그러므로 내가 이해하는 한, 새로운 운영 객체와 매개 변수를 수동으로 설정하면 내 문제가 해결되지 않습니다.
문제는 직렬화입니다 RichTextBox 생성 부분 추가 할 수없는 객체 TextBlock.inlines. 따라서, 사형화 된 물체를 다음으로 설정하는 것은 불가능합니다. TextProperty 의 텍스트 블록.
해결책
TextBlock이 FlowDocument를 표시 할 수 있다는 것을 알고 있습니다
당신이 그것을 생각하게 만드는 것은 무엇입니까? 나는 그것이 사실이라고 생각하지 않습니다 ... TextBlock
입니다 Inlines
속성, 그것은 an입니다 InlineCollection
. 따라서 포함 할 수 있습니다 Inline
S ...하지만 a FlowDocument
, 내용은 Blocks
인스턴스를 포함하는 속성 Block
. 그리고 a Block
아닙니다 Inline
다른 팁
다음과 같이 객체를 작성하고 추가하십시오.
Run run = new Run("Courier New 24");
run.Foreground = new SolidColorBrush(Colors.Maroon);
run.FontFamily = new FontFamily("Courier New");
run.FontSize = 24;
txtFont.Inlines.Add(run);
당신의 경우 흐름 문서 그랬어 사형화, 그것은 당신이 유형의 객체를 가지고 있음을 의미합니다. FlowDocument
, 오른쪽? 텍스트 블록의 텍스트 속성을이 값으로 설정하십시오. 물론, 당신은 이것을 할 수 없습니다 txtFont.Text = ...
, 이것은 줄에만 적용되므로. 다른 유형의 객체의 경우 종속성 장비를 직접 설정해야합니다.
txtFont.SetValue(TextBlock.TextProperty, myFlowDocument)
다음은 스타일을 비행기를 할당하여 텍스트 블록의 모양을 설정하는 방법입니다.
// Set Weight (Property setting is a string like "Bold")
FontWeight thisWeight = (FontWeight)new FontWeightConverter().ConvertFromString(Properties.Settings.Default.DealerMessageFontWeightValue);
// Set Color (Property setting is a string like "Red" or "Black")
SolidColorBrush thisColor = (SolidColorBrush)new BrushConverter().ConvertFromString(Properties.Settings.Default.DealerMessageFontColorValue);
// Set the style for the dealer message
// Font Family Property setting is a string like "Arial"
// Font Size Property setting is an int like 12, a double would also work
Style newStyle = new Style
{
TargetType = typeof(TextBlock),
Setters = {
new Setter
{
Property = Control.FontFamilyProperty,
Value = new FontFamily(Properties.Settings.Default.DealerMessageFontValue)
},
new Setter
{
Property = Control.FontSizeProperty,
Value = Properties.Settings.Default.DealerMessageFontSizeValue
},
new Setter
{
Property = Control.FontWeightProperty,
Value = thisWeight
},
new Setter
{
Property = Control.ForegroundProperty,
Value = thisColor
}
}
};
textBlock_DealerMessage.Style = newStyle;
스타일 섹션을 제거하고 속성을 직접 설정할 수 있지만 프로젝트 전체에서 모양을 구성하는 데 도움이되는 스타일로 묶인 물건을 유지하는 것을 좋아합니다.
textBlock_DealerMessage.FontWeight = thisWeight;
HTH.