I am trying to create a WPF application that has a richtextbox which accepts dictations from the user as its input.
I want to use this code for the SpeechRecognized event for an an object of the SpeechRecognitionEngine class.
private void speechRecognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
e.Result.Text = rtb.Text; //rtb is an object of the RichTextBox class
}
The problem is that there is no Text property for the RichTextBox class. Is there any way of fixing this? Thanks in advance
Try this:
private void speechRecognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
rtb.AppendText(e.Result.Text);
}
This is a well documented problem and there are many different solutions for it. You can find a large number of possible solutions in the answers to the RichTextBox (WPF) does not have string property “Text” question here on Stack Overflow.
However, my preferred method would be to declare a Text Attached Property for the RichTextBox class. Please see the Attached Properties Overview page on MSDN to find out more about Attached Properties. You can find out what code to use in your Text Attached Property for the RichTextBox class in the RichTextBox Text property where are you hiding? tutorial on C# Disciples website.
RichTextBox contents can be set via Document property. You can find more details on MSDN
Here is an example from the link provided above. It creates a new document and a paragraph for it, then assigns the document to RichTextBox:
// Create a simple FlowDocument to serve as content.
FlowDocument flowDoc = new FlowDocument(new Paragraph(new Run("Simple FlowDocument")));
// Create an empty, default RichTextBox.
RichTextBox rtb = new RichTextBox();
// This call sets the contents of the RichTextBox to the specified FlowDocument.
rtb.Document = flowDoc;
// This call gets a FlowDocument representing the contents of the RichTextBox.
FlowDocument rtbContents = rtb.Document;
Related
I am creating a View Controller that records the Phone Number or Email adress of the user, and I want the placeholder of the textfield to change when they select either the "Phone" button, or the "Email" button.
This is just the button that is supposed to change the placeholder
void PhoneSelectBtn(object sender, EventArgs e)
{
EmailPhoneBox.AttributedPlaceholder = new NSAttributedString("Phone");
}
and every time I run the application, it crashes and this is the error that I get:
Objective-C exception thrown. Name: NSUnknownKeyException Reason: [<UIViewController 0x7f813ec3b870> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key EmailPhoneBox.
Native stack trace:
I have tried other options, such as using a segmented control (obviously it is a little different then setting up a button), and I get the same result. I have changed button methods, classes, and the same result occurs every single time. There are no unnecessary events lingering that aren't attached to anything either. Out of ideas. If one could explain step by step what to do, that would be great. I am sure that it isn't a hard thing to do, but I am just learning, and am finding it hard to find applicable documentation on small things like this. Thanks, Josh
It seems that just like with many other Xamarin features which seem like they should be added but aren't, this one needs a custom renderer.
See this link for more.
Another option is
Set the placeholder string to your Editor's Text in Xaml Then in Code behind file:
InitializeComponent();
var placeholder = myEditor.Text;
myEditor.Focused += (sender, e) =>
{
// Set the editor's text empty on focus, only if the place
// holder is present
if (myEditor.Text.Equals(placeholder))
{
myEditor.Text = string.Empty;
// Here You can change the text color of editor as well
// to active text color
}
};
myEditor.Unfocused += (sender, e) =>
{
// Set the editor's text to place holder on unfocus, only if
// there is no data entered in editor
if (string.IsNullOrEmpty(myEditor.Text.Trim()))
{
myEditor.Text = placeholder;
// Here You can change the text color of editor as well
// to dim text color (Text Hint Color)
}
};
I have a RichTextBox control in my view. I'm using code-behind (UI logic only) to format the RTF within my RichTextBox which is working from a 'Format' button click event which instantiates a TextRange:
private void _btnFormat_Click(object sender, RoutedEventArgs e)
{
TextRange rangeOfText = new TextRange(richTextBoxArticleBody.Document.ContentStart, richTextBoxArticleBody.Document.ContentEnd);
rangeOfText.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Black);
rangeOfText.ApplyPropertyValue(TextElement.FontSizeProperty, "12");
rangeOfText.ApplyPropertyValue(TextElement.FontFamilyProperty, "Arial");
rangeOfText.ApplyPropertyValue(TextElement.FontStyleProperty, "Normal");
rangeOfText.ApplyPropertyValue(Inline.TextDecorationsProperty, null);
}
I want to also remove any tables within the RTF. Can I use the same approach maybe from the Table class to remove tables from my RichTextBox? Thanks
You'll have to climb down the Blocks and get the descendants
of the FlowDocument and get all the Tables and then remove them from the its Parent.
Ok, if anyone is trying to achieve this I don't think it's possible. Maybe you can iterate over a simple table in an Rtf string and remove the tags but if you can't determine user input the Rtf is by far too complex. Therefore here's my solution (of sorts...)
private void _btnFormat_Click(object sender, RoutedEventArgs e)
{
TextRange rangeOfText = new TextRange(richTextBoxArticleBody.Document.ContentStart, richTextBoxArticleBody.Document.ContentEnd);
rangeOfText.ApplyPropertyValue(Table.BorderThicknessProperty, "3");
rangeOfText.ApplyPropertyValue(Table.BorderBrushProperty, Brushes.Red);
}
In the 'Format' button click event I've set table borders to Red. On my save back to the database method I've used this simple if statement:
private void SaveToDbCommandAction()
{
if(PastedText.Contains("trowd"))
{
Xceed.Wpf.Toolkit.MessageBox.Show("Cannot save Article. Please remove pasted tables");
}
else
{
SaveToDb(RTBText);
}
}
Therefore when the user pastes in a table they are warned via the red cell borders. This is particularly useful if they paste a table with invisible borders and can't actually see the table. The If statement then determines whether the Rtf string contains a 'trowd' tag therefore preventing the save.
I'm using a 'Paste' button command in my view Model to copy RTF from the clipboard. PastedText is my string property that a RichTextBox is bound to in my view:
private void FormatPastedTextCommandAction()
{
PastedText += Clipboard.GetText(TextDataFormat.Rtf);
}
This works and the text is pasted on pressing the Paste button. However, I want to lock down the formatting on the paste function and remove all formatting from the pasted RTF string (colour, italics, set to black Arial 12).
I would just use PastedText += Clipboard.GetText();
to get the plain text but it pastes in at a different font size and I need it in RTF format. I've looked at iterating over the RTF string and doing a find/replace on font size, colour etc. but the RTF is very complex even for a couple of words.
Is there any way around this? Thanks
In the end I used code behind in the view to strip formatting from the RichTextBox itself using a 'Format' button:
private void _btnFormat_Click(object sender, RoutedEventArgs e)
{
TextRange rangeOfText = new TextRange(richTextBoxArticleBody.Document.ContentStart, richTextBoxArticleBody.Document.ContentEnd);
rangeOfText.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Black);
rangeOfText.ApplyPropertyValue(TextElement.FontSizeProperty, "12");
rangeOfText.ApplyPropertyValue(TextElement.FontFamilyProperty, "Arial");
rangeOfText.ApplyPropertyValue(TextElement.FontStyleProperty, "Normal");
rangeOfText.ApplyPropertyValue(Inline.TextDecorationsProperty, null);
rangeOfText.ApplyPropertyValue(Paragraph.MarginProperty, new Thickness(0));
}
This does a good job and doesn't really break the MVVM pattern as the code is UI logic only.
If I copy some text with different format and paste it to my richtextbox it is not plain I mean its format will be copied as well.
Is there anyway I can copy-paste as a plain text?
By the way my program is on WinForm
thanks for any answer
you must use WinForm RichTextBox (not in UI, just in code), even if you are on WPF, in order to convert RTF to plain text. Use this method in your Copy event.
C# code :
private String ConvertRtfToText()
{
System.Windows.Forms.RichTextBox rtfBox = new System.Windows.Forms.RichTextBox();
rtfBox.Rtf = this.rtfData;
return rtfBox.Text;
}
VB.Net Code :
Private Function ConvertRtfToText() As String
Dim rtfBox As RichTextBox = New RichTextBox()
rtfBox.Rtf = Me.rtfData
Return rtfBox.Text
End Function
source : http://msdn.microsoft.com/en-US/en-en/library/vstudio/cc488002.aspx
I recently had the same issue. I did want to retain some of the formatting, i.e. paragraphs and line feeds, but I required all the addition text format to be removed.
I'm working in WPF but the RichTextBox interface is the same. I have created a button that will allow users to select some text and remove the formatting. It is very simple, you just need to use the ClearAllProperties() method on the TextSelection object.
C# Code (WPF):
private void ClearFormat_Click(object sender, RoutedEventArgs e)
{
rtbText.Selection.ClearAllProperties();
}
This is a super easy solution but perhaps not super elegant...
1) Add a plain textbox to your form and make it hidden
2) Create a button to remove the formatting (or you can do this
automatically when the text is pasted)
3) In the OnClick (or OnPaste) code just copy the text from the rich
textbox control to the plain textbox control then copy the text
from the plain textbox back to the rich textbox control (see example
below)
private void btnRemoveFormatting_Click(object sender, EventArgs e)
{
txtPlainText.Text = txtRTF.Text;
txtRTF.Text = ""; // Required - this makes sure all formatting is gone
txtRTF.Text = txtPlainText.Text;
}
I just found myself a new challenge:
Make a Word Processor that is in handling more like the web than plain text.
Designing a nice framework for this is what i cant wait to start with, but i do need to know what the possibilities are at the GUI side (it will probably have loads of GUI challenges).
So the basic thing that I need some sort of Control where I can make parts of my text clickable / mouse-over-able.
I'm kinda new to WPF and not sure how to do this.
Has anybody an idea how to make this?
Are there examples?
Are there already controls for this?
Thanks in advance
EDIT:
I found out some way to do it with a richtextbox:
// Create a FlowDocument to contain content for the RichTextBox.
FlowDocument myFlowDoc = new FlowDocument();
// Add paragraphs to the FlowDocument.
Hyperlink myLink = new Hyperlink();
myLink.Inlines.Add("hyperlink");
myLink.NavigateUri = new Uri("http://www.stackoverflow.com");
// Create a paragraph and add the Run and hyperlink to it.
Paragraph myParagraph = new Paragraph();
myParagraph.Inlines.Add("check this link out: ");
myParagraph.Inlines.Add(myLink);
myFlowDoc.Blocks.Add(myParagraph);
// Add initial content to the RichTextBox.
richTextBox1.Document = myFlowDoc;
I now get a nice hyperlink in my textbox... except when i click it, nothing happens.
what am i missing here?
You can use the Hyperlink class. It's a FrameworkContentElement, so you can use it in a TextBlock or FlowDocument or anywhere else you can embed content.
<TextBlock>
<Run>Text</Run>
<Hyperlink NavigateUri="http://stackoverflow.com">with</Hyperlink>
<Run>some</Run>
<Hyperlink NavigateUri="http://google.com">hyperlinks</Hyperlink>
</TextBlock>
You may want to look at using a RichTextBox as part of your editor. This will host a FlowDocument, which can contain content such as Hyperlinks.
Update: There are two ways to handle clicks on the Hyperlink. One is to handle the RequestNavigate event. It is a Routed Event, so you can either attach a handler to the Hyperlink itself or you can attach one to an element higher in the tree such as the Window or the RichTextBox:
// On a specific Hyperlink
myLink.RequestNavigate +=
new RequestNavigateEventHandler(RequestNavigateHandler);
// To handle all Hyperlinks in the RichTextBox
richTextBox1.AddHandler(Hyperlink.RequestNavigateEvent,
new RequestNavigateEventHandler(RequestNavigateHandler));
The other way is to use commanding by setting the Command property on the Hyperlink to an ICommand implementation. The Executed method on the ICommand will be called when the Hyperlink is clicked.
If you want to launch a browser in the handler, you can pass the URI to Process.Start:
private void RequestNavigateHandler(object sender, RequestNavigateEventArgs e)
{
Process.Start(e.Uri.ToString());
}
Note you also need to set the following properties on your RichTextBox or the hyperlinks will be disabled and won't fire off events. Without IsReadOnly you need to Ctrl-click the hyperlinks, with IsReadOnly they fire with a regular left-click.
<RichTextBox
IsDocumentEnabled="True"
IsReadOnly="True">
The simplest way is to handle RequestNavigate event like this:
...
myLink.RequestNavigate += HandleRequestNavigate;
...
private void HandleRequestNavigate(object sender, RoutedEventArgs e)
{
var link = (Hyperlink)sender;
var uri = link.NavigateUri.ToString();
Process.Start(uri);
e.Handled = true;
}
There are some issues with starting a default browser by passing url to the Process.Start and you might want to google for a better way to implement the handler.