当循环访问 C# Winform 控件时,我无法在富文本框控件上使用 Rtb 属性
When Iterating Through C# Winform Controls I Cannot Use the Rtb Property on Rich Text Box Controls
我正在尝试将一些富文本格式 (RTF) 文本放入富文本框 (RTB) 中。我正在迭代几个 winform 控件来获取我需要的 RTB。我可以使用 RichTextBox.Text 属性 将普通文本添加到文本框,但是当我尝试使用 RichTextBox.Rtb 属性 向其添加 RTF 文本时出现错误说该控件不存在(“控件不包含 Rtb 的定义”)。在下面的代码示例中,为什么我的“rtbControl”没有 Rtb 属性,即使控件应该是RichTextBox?如何为该控件使用 Rtb 属性/设置 RTF 文本?
// RTF string I want to display in the RTB
string some_rtb_text = @"{\rtf1\ansi This is some \b bold\b0 text.}";
foreach (Control rtbControl in GlobalVars.myUserControl1.Controls) // iterate through all the controls and find the one I want
{
if (rtbControl is RichTextBox & rtbControl.Name == "the_text_box_I_want_to_use") // Making sure the control is a RichTextBox
{
rtbControl.Rtb = some_rtb_text; // it's telling me that rtbControl does not contain a definition for Rtb
}
}
在 if 语句中它检查 rtbControl
是否是一个 RichTextBox。如果是,您需要创建一个新的 RichTextBox 变量才能使用 RichTextBox 属性,例如 Rtf
或 SelectedRTF
.
if (rtbControl is RichTextBox & rtbControl.Name == "name_of_control") // Making sure the control is a RichTextBox
{
RichTextBox rtb = rtbControl as RichTextBox;
rtb.Rtf = some_rtb_text;
}
Rhys Wootton 的回答是正确的,恕我直言回答了你的问题,但可以稍微简化一下:
if (rtbControl.Name == "name_of_control" && rtbControl is RichTextBox rtb)
{
rtb.Rtf = some_rtb_text;
}
我正在尝试将一些富文本格式 (RTF) 文本放入富文本框 (RTB) 中。我正在迭代几个 winform 控件来获取我需要的 RTB。我可以使用 RichTextBox.Text 属性 将普通文本添加到文本框,但是当我尝试使用 RichTextBox.Rtb 属性 向其添加 RTF 文本时出现错误说该控件不存在(“控件不包含 Rtb 的定义”)。在下面的代码示例中,为什么我的“rtbControl”没有 Rtb 属性,即使控件应该是RichTextBox?如何为该控件使用 Rtb 属性/设置 RTF 文本?
// RTF string I want to display in the RTB
string some_rtb_text = @"{\rtf1\ansi This is some \b bold\b0 text.}";
foreach (Control rtbControl in GlobalVars.myUserControl1.Controls) // iterate through all the controls and find the one I want
{
if (rtbControl is RichTextBox & rtbControl.Name == "the_text_box_I_want_to_use") // Making sure the control is a RichTextBox
{
rtbControl.Rtb = some_rtb_text; // it's telling me that rtbControl does not contain a definition for Rtb
}
}
在 if 语句中它检查 rtbControl
是否是一个 RichTextBox。如果是,您需要创建一个新的 RichTextBox 变量才能使用 RichTextBox 属性,例如 Rtf
或 SelectedRTF
.
if (rtbControl is RichTextBox & rtbControl.Name == "name_of_control") // Making sure the control is a RichTextBox
{
RichTextBox rtb = rtbControl as RichTextBox;
rtb.Rtf = some_rtb_text;
}
Rhys Wootton 的回答是正确的,恕我直言回答了你的问题,但可以稍微简化一下:
if (rtbControl.Name == "name_of_control" && rtbControl is RichTextBox rtb)
{
rtb.Rtf = some_rtb_text;
}