I know how to accomplish this with some code behind my XAML but I am wondering if it is possible to restrict what characters are entered in a textbox using pure XAML with no C#?
I have tried to research this but have found nothing, So I am assuming its not possible so just checking here.
Could write a markup extension returning a filter in the text change event. It's fairly messy and still requires the code for the extension, but you could then provide the limited characters in XAML.
Alternatively an attached property could provide the same functionality and is probably a bit cleaner in this case.
Lastly you could subclass the TextBox control and make the logic and internal part of the control that can be configured with a dependency property.
You can inherit the textbox "Behavior<TextBox>" and add your logic in OnPreviewTextInput event to check for validation.
Related
I have some strings that contain line breaks, and I would like to keep this formatting in each ListBox item that the strings are applied to.
Is there any way to do this?
Thanks
The ListBox in winforms doesn't support multiline/text wrapping. If you want that kind of behaviour you probably need to do a custom control or there may be a third party control.
There's a sample implementation at http://www.codeproject.com/articles/2695/an-editable-multi-line-listbox-for-net. It's old so there may be better implementations out there/at least you can see what's involved.
I am currently stuck on an issue that I have been unable to find an answer for. It involves 'overriding' built-in TextBox keyboard functions using MVVM. Here's my issue:
I have a TextBox that the users enters text into during runtime. I'm looking to implement keyboard shortcuts, or input bindings with this TextBox. I started out by using what seems to be the standard ICommand interface based approach, which I implemented simply as:
<TextBox.InputBindings>
<KeyBinding Key="Up" Command="{Binding testCommand}" Modifiers="Ctrl" />
</TextBox.InputBindings>
The idea is that I execute the command associated with the ICommand property as set in the ViewModel. However, the TextBox class already contains a baked in function for CTRL+UP which, as you may know, moves the caret to the beginning of the TextBox entry field. This function executes in addition to my Command, resulting in my desired changes, but also the caret moving.
Before MVVM, I would simply use the PreviewKeyDown event in Code-Behind, detecting the desired key combinations and using
e.Handled = true;
to stop the TextBox from firing its built in Command. This isn't an optimal solution, however, as it probably violates MVVM principles. It would also be difficult to implement in tandem with InputBindings declared in XAML.
During my research, I found an article that describes using a class provided by Blend that allows for executing a Command based off an event, potentially allowing me to listen for the PreviewKeyDown event, which fires before the built-in functions, but this would mean that I would not be declaring my key bindings in XAML, as the syntax does not seem to support keypress specific conditions, or InputBindings. I would have to do all key combination processing logic in the ViewModel, which seems like something the View should be doing.
Further research has led me to an interesting new area which involves intercepting and replacing certain 'ApplicationCommands' with a Command that always returns false on CanExecute, effectively removing the function. I was able to locate a case where someone wanted to replace the default CTRL+Z functionality. An abridged version of the full question shows the basic idea:
textBox.CommandBindings.Add(new CommandBinding(ApplicationCommands.Undo,
UndoCommand, CanUndoCommand));
Research of this ApplicationCommands class led me to a few other classes, one of which relates more directly to my issue: ComponentCommands. MSDN describes that class as containing (among other things)
ComponentCommands.MoveToHome
which would fit my Ctrl+Up command's built-in function. Using the syntax in the SO question I linked previously, I could theoretically prevent that command from executing, which is a step in the right direction. However, I'm hoping to make the key combinations that trigger my Command in my ViewModel customizable via ViewModel properties that the InputBindings would be bound to in XAML. If I implemented this approach, it would mean that I could not know ahead of time which built in functions might conflict with the user's chosen key bindings.
This was naturally resolved for me before I switched to MVVM by handling the arguments in the event handler in Code-Behind, as mentioned previously. Any key combinations I wrote into the PreviewKeyDown event handler that I had a special action for set the e.Handled to true, effectively preventing any possible built-in command that would follow once the method finished from executing after the event handler finished.
Is there some way I could implement this functionality, using InputBindings declared in XAML? What are my options?
Some ideas:
Perhaps I could expose the event handler for PreviewKeyDown on my TextBox, and inside the method I iterate through all of the TextBox's InputBindings, looking for provided key combinations that match the provided key press, and if found, I execute the associated command and set e.handled to true? I'm not familiar with manipulating InputBindings from Code-Behind, so I'm not sure how practical this would be, or if it would place too much load on the application (imagine a user holding down a key). It also seems a bit strange in terms of organization to set it up this way. I could see a situation happening where the input bindings fire twice.
I could also make a list of all the built-in commands that I'd want to always have around, even if the user set a key combination that conflicted, and disable the rest. That seems like a bad idea, as it would be quite laborious, and also could mess with something I couldn't anticipate.
Perhaps there's a way that I could calculate which built-in commands would conflict with the current input bindings and disable those, to be calculated each time the user sets the bindings?
I'm still learning MVVM and WPF, so I suspect that I may be missing something obvious or simply looking at it the wrong way. Any help would be greatly appreciated.
Edit:
It has been suggested that my question is a duplicate of this one. I have reviewed the answer and determined that the approach used is definitely a step in the right direction. I could use the attached object to implement the PreviewKeyDown handling without losing functionality of InputBindings in XAML. However, I do have some concerns.
It seems that the resolution was to move the InputBindings to the UserControl, and implement an attached object that would handle PreviewKeyDown. I have multiple TextBoxes in my UserControl which will need their own set of InputBindings, some of which would conflict with one another should they be moved to the UserControl level.
I can only conclude that the reason it was moved away from the TextBox was that the attached object could not be applied directly to the TextBox for some reason. If I was to attempt this, would I have to create some encompassing element that had the attached object that would hold each TextBox? Why can't the TextBox use the attached object itself?
I feel like I'm going to reinvent wheel so I would like to know if WPF has bult-in support for what I'm trying to achieve. I'm building an app that will allow people to enter some text in a textbox, and then see it formatted in a textblock.
I would like that the user be able to format the text himself by inputing things such as
This [BusinessSpecificStyle] is [/BusinessSpecificStyle] a sample text
My purpose is to be able to easily change the presentation of all my documents by simply changing the underlaying rules in BusinessSpecificStyle. However I don't know what is the best way to implement that with WPF. I was thinking of using a BBCode parser like this one but supposing I go that way, I don't see how I will be able to convert the resulting XAML into TextBlock children programatically, and I seriously wonder if there isn't some kind of built in support for that.
Thanks for your help
IValueConverter is what you are looking for.
Create the converter and format your text based on the bindings passed from the XAML.
You can get multiple samples over the net for creating IValueConverter. Refer to the link here and here to get you started.
Not sure if you are asking for Converter here. To me it reads that you want to control the style of a block of text depending on some background and common style?
If that is the case, you want to set the inlines of your text block to seperate your text into run elements, which can reference a specific style resource.
<TextBlock>
<TextBlock.Inlines>
<Run>This</Run>
<Run Foreground="{StaticResource BusinessSpecificStyleForeground}">is</Run>
<Run>a sample text</Run>
...
in this case, you create a resource which defines the binding styles for run or bind the Style in it's entirety.
Apologies if I am making up a new question, I see you've marked an answer but wanted to add this just in case.
I have two doubts about the autocomplete feature of textboxes in C#.
First, I want to display the full list, not only the ones that start with the given text, and secondly I want to prevent the auto-complete of specific options (some are category titles).
I've been checking the textbox properties and there's nothing related to it, so probably the main question could be, Is there a way to modify / override the textbox events in order to handle the auto-complete actions? (I don't know if it applies to show the full list too)
I assume you're asking about a winforms textbox, as I dont think the WPF textbox supports autocomplete at all.
The base TextBox class will not support doing what you want, so you could in theory attempt to override all of the functionality in the TextBox class to do what you want, but the better idea would be to create a new custom control that inherits from TextBoxBase and implement the autocomplete behavior the way you want it.
I'm not sure about displaying the full list (perhaps a combobox or similar is more suited to this?) but you can definitely do something like this to swap which list of possible items can be displayed.
Another option, though one I like less, is to remove items you don't want to display at a given time from the collection dynamically, like this: textBox.AutoCompleteCustomSource.Remove("ACategoryTitle")
I could foresee that approach having many problems with trying to rebuild the list constantly. I would probably create a subclass of AutoCompleteStringCollection that wraps some LINQ code to nicely select the union of some lists and not others to display in the textbox.
I decided to build my own autocomplete tool with the help of a simple listbox and events, then I could achieve what I was expecting..
The CodingGorilla's answer probably leads to a better solution if you want something more decent, in my case for speed reasons I decided to do it that way but I'll mark his answer as the accepted in order to help other people who have the same doubt and they could consider that point..
This supposedly easy task gave me some headache. I simply want to let the user enter any text that succeeds float.TryParse into a Textboxish control.
I could use a normal TextBox and check the Text in some btnOK_Click, but this is obviously lame. Also, there is a nice built-in MaskedTextBox control, but I failed to set it's mask to be equal to float.TryParse. Also, it seems to check for validity only when a focus change occurs.
Digging around on the net brought some interesting ideas, but none of them as nice as I would like.
How did you solve this problem? Did I simply miss an obvious solution, or do I have to implement this functionality myself?
I'm aware of a few similar threads on SO, but there was no feasible solution to be found.
Update: Yes, WinForms.
Edit
Well that makes it alot easier... Just add a Validating Event Handler to your textbox
and do the TryParse in the code behind. If its invalid, prompt the user as such.
Validating will fire when the user is finished typing and moves focus from the TextBox so if you need to do on the fly checking, you could handle the TextChanged or on of the KeyPress/KeyUp Event handlers instead
Original
Is this in asp.net or winforms/wpf
If its asp.net, you could use a combination of RegularExpressionValidator (to account for comma seperation, 1 decimal point, etc...) and a RangeValidator to set the min/max values for a float.
Aside from that, the only way to guarantee it would be to wrap the textbox in an updatepanel, stick a CustomServerValidator on it, and in the server validate function, do a TryParse on the TextBox.Text value, if it succeeds, IS VALID, if it fails, NOT VALID
Be careful using Validating and validating to false. You might find that, unless you enter valid data, you can't move focus off the textbox which is a really big usability pain.
I solve this by simply trying a TryParse() on LostFocus and if the TryParse fails I color the textbox background a reddish tint to make it obvious that something is wrong.