UWP: Binding + TextChanging = JIT win32 exception - c#

I am 100% sure I am doing this the wrong way and this problem is "by design".
I want to have a Slider and a TextBox that displays its value. The user can either use the Slider, or manually enter a number in the TextBox.
I also wanted to take advantage of the TextChanging event to ignore any non-numerical entries. TextChanged would only function after a user has entered something and it's not a preferable scenario, and KeyDown would not capture other methods of input like ink or speech.
So I have this:
<StackPanel>
<Slider x:Name="Size" Value="100" Maximum="100" Minimum="0" />
<TextBox x:Name="SizeText" Text="{Binding ElementName=Size,Path=Value,Mode=TwoWay}" TextChanging="SizeText_TextChanging" />
</StackPanel>
Where "SizeText_TextChanging" is simply an empty block of code right now:
private void SizeText_TextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
{
// Nothing Here.
}
This code builds, but at startup the app throws a JIT unhandled win32 exception and closes.
Changing TextChanging to TextChanged works fine, but again I prefer to get TextChanging to work (or something similar) to give a better user experience.
"Mode" also has no effect. I tried all three different Modes, all crash. By removing the binding altogether and giving the Text property any value works fine.
I also thought that maybe having the TextChanging event handler empty is the problem, so I borrowed the code below from here but the app still crashes:
private void SizeText_TextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
{
if (!Regex.IsMatch(sender.Text, "^\\d*\\.?\\d*$") && sender.Text != "")
{
int pos = sender.SelectionStart - 1;
sender.Text = sender.Text.Remove(pos, 1);
sender.SelectionStart = pos;
}
}
Like I said, I am probably approaching this the wrong way. I am just starting to learn UWP and C# so I am a total noob. But I have read everything I could about TextChanging and it simply talks about rendering the value and the associated cautions of what not to write within the TextChanging event. So while it sounds like the app is being thrown into a loop trying to read the value of the slider and trying to see what the TextChanging event says, I don't see how to fix it. Please help!
Thank you

I don't know why this is happening, but a workaround is to register the TextChanging event handler only once SizeText (or the page) has loaded and using x:Bind instead of Binding:
XAML
<TextBox x:Name="SizeText" Text="{x:Bind Size.Value, Mode=TwoWay}" Loaded="SizeText_Loaded"/>
CS
private void SizeText_Loaded(object sender, RoutedEventArgs e)
{
SizeText.TextChanging += SizeText_TextChanging;
}
private void SizeText_TextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
{
}

I meet the same problem but this solution doesn't works for me.
As #Mushriq, I use _TextChanging() to ignore any non-numerical entries in a form.
But my form contains a lot of numeric fields and also a master-detail part, which contains 2 of these fields.
The problem is that I enter in the _Loaded the first time that I display a part, but not for the other parts. When I display existing parts there is no problem, but if I add a new part I get the exception.
Is there a way to adapt the solution to my case?

Related

AvaloniaUI - How to choose folder

I am using AvaloniaUI https://avaloniaui.net/docs/
I have researched their docs but it seems I can not find how can I make button which when pressed is forcing you to choose a folder.
Is it even possible and if so how, is there any example ?
I toyed with AvaloniaUI some time ago, got it working under Windows and struggled getting it working under Mac.
Nevertheless, I've seen your other question where you seem to get the dialog opened. Still, for the future:
In your XAML you place a button in a place you please:
<Button Content="Choose folder..." Margin="3" Name="FolderButton" />
Perhaps there is another way of getting it working, the following worked for me:
In your code you need to create a variable that represents your button:
private Button _folderButton;
In your constructor or in your InitializeComponent() method you find the button from XAML and assign it to your variable:
_folderButton = this.FindControl<Button>("FolderButton");
You also assign an event handler for Click event:
_folderButton.Click += FolderButtonClick;
You can immediately add the unsubscribe in your destructor:
_folderButton.Click -= FolderButtonClick;
Now you provide an event handler declaration and implementation:
public void FolderButtonClick(object sender, RoutedEventArgs e)
{
...
}
You may use http://avaloniaui.net/api/Avalonia.Controls/OpenFolderDialog/ - as you've already found out in your other question.
This even handler can be made async if you have any await operations inside.
I hope this helps.

c# - How to access a variable from outside its class in a method in some other class?

I am a beginner in c# programming and I am developing windows phone application after reading some tutorials.
My idea is when the user clicks a button in a windows page, some other button in other windows phone page must change color from red to green.
Pardon me if I am too Basic.
This I have defined in a page named "IndexPage.xaml"
<Button x:Name="One_green"
Content="1"
Background="Green"
Click="One_Click"
/>
<Button x:Name="One_red"
Content="1"
Background="Red"
Click="One_Click"
/>
Now I see red color button in my window as green button is hidden in the back.
Now, the following code is from another windows phone page "1.xaml"
<Button Content="GO" Click="Button_Click"/>
Now when the user clicks the "GO" Button I want the button to change to red to green in "IndexPage.xaml". So I tried a code something like this in "1.xaml.cs"
private void Button_Click(object sender, RoutedEventArgs e)
{
One_red.Visibility = Visibility.Collapsed;
One_green.Visibility = Visibility.Visible;
}
But I am not able to access the "One_red" or "One_green" button in the above code. Please shed me directions.
Also I want that code to execute only once. (i.e.) when the IndexPage.xaml loads again I want that button to be green always.
Thank you very much in advance.
Please tell me if some other details are required.
You could define a public or internal static variable inside the "Index.xaml" class specifying what button will show on load until otherwise specified. This variable could be accessed outside the class, and possibly even outside the project depending on the modifier chosen. The constructor of the "Index.xaml" class could have code to reset it to the default to ensure it only happens on the next creation of the page. If you aren't creating a new page everytime, you would have to put the default resetters in a method called when you want to bring it to foreground.
It seems to me that you are trying to learn, rather than having a SPEC to follow and implement.
Because of that, and because you are starting with C# in 2014 (almost 2015),
it will be quite beneficial for you to jump straight to data-binding declarative over imperative, going MVVM (MVVx) over MVC (MVx).
XAML was designed around this pattern. It's the natural way of doing things in XAML, a perfect fit and the perfect platform to learn the pattern.
It requires lots of learning, thinking, and re-learning, but it will open your eyes to modern programming techniques.
That said... there are too many ways of doing what you asked for, and while none are exactly wrong, there are 2 current trends in .Net/C#/MsTech which IMO are NOT a waste of your time:
Functional Reactive Programming and OOP/MVVx (the x is for whatever).
Examples are ReactiveUI, Reactive Extensions, PRISM, Caliburn.Micro and many more. They can be combined, the same way you can combine traditional event-driven/event callbacks with MVVM and/or Reactive Programming. However, I would advise against it.
I'll start with the most documented way.
Look at Data binding for Windows Phone 8. It was the first result when I googled "windows phone 8 xaml data binding," and deals with Colors and controls.
If you follow that example and add a resource to your application, you are done.
Of course, you can still use event => onClick + static class to hold the value in between View instances, but if I was right on the assumption that you are trying to learn, I wouldn't go that route.
Sorry if I drifted. :)
You may not be able to access the button click event because it is private, you may need to make it protected or public, the default access specifier would probably be ok as well.
public void Button_Click(object sender, RoutedEventArgs e)
or default would be:
void Button_Click(object sender, RoutedEventArgs e)

How to make password box non-editable in wpf

I need to make password box as non-editable in wpf.
I used
IsEnabled = false
But it is affecting my style some blur effect came because of that...
Is there any other way to achieve this ?
I know this is two years old, but I had the same need and solved it this way:
The combination of these two properties, both set to false, will prevent entry/editing in the control, w/o affecting your desired style:
Focusable, IsHitTestVisible
You can handle the PreviewTextInput event, preventing the user from entering text. Like so:
Xaml:
<PasswordBox PreviewTextInput="HandleInput"/>
Codebehind:
private void HandleInput(object sender, TextCompositionEventArgs e) {
e.Handled = true;
}
One solution is to make a custom functionality to mimic the IsReadOnly.
There are couple things to take care of - e.g. clipboard pasting
also.
You'll get similar behavior by defining some attached property (e.g. IsPasswordReadOnly or just the same) - which would work out all that's required.
Here is a good starting example - which could, should I think work for Password box as well - but I haven't tried it and you gotta test yourself.
Readonly textbox for WPF with visible cursor (.NET 3.5)
You'd have to replace references to TextBox with PasswordBox, rename it to IsReadOnly - and I think the rest might work the same.
And you use it like...
<PasswordBox my:AttachReadOnly.IsReadOnly="True" />
Pretty simple..
Set an event handler for PreviewTextInput in your XML like so:
PreviewTextInput="PasswordBoxOnPreviewTextInput"
And within that method:
private void PasswordBoxOnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (m_DisablePasswordBox)
e.Handled = true;
}
It will now prevent you from typing anything in :)

Second TextBox showing same Text Selection as first

Long time listener, first time caller here. I'm having a strange issue with the TextBox in WinRT C#/XAML that I hope someone may be able to help me with.
Basically, I'm working on creating a Custom Control that essentially requires a second TextBox to be a copy of the first, including showing the same Text, and showing the same Selected Text. Obviously for the Text requirement I simply respond to the TextChanged event on the first TextBox and set the Text of the second TextBox to the Text from the first, which works great.
For the Selected Text requirement I started with a similar solution, and my code for this is as follows:
void TextBox1_SelectionChanged(object sender, RoutedEventArgs e)
{
this.TextBox2.Select(this.TextBox1.SelectionStart, this.TextBox1.SelectionLength);
}
This seemed to work pretty well when initially used with a mouse:
But I'm having a problem when selecting text with Touch. I double-tap within the TextBox to create the first "anchor" as you do in Touch, then drag to begin the selection; but I only ever manage to select a single character normally before the selection stops. The TextBox doesn't lose focus exactly, but the behaviour is similar to that; the selection anchors disappear and I can't continue selecting anything unless I re-double-tap to start a new selection. If I remove the code to select text in TextBox2 then the Touch selection behaves perfectly in TextBox1.
I've been trying to fix this for a while and cannot, I'm not sure if I can get the desired behaviour with WinRT TextBoxes. Does anyone have any ideas? Or perhaps another way to implement a solution with two TextBoxes with this behaviour?
Thanks a lot.
So this is far from an answer, but discovered a few things that maybe will help you or others come up with a potential workaround. Apologies if these are things you've already seen and noted.
First, it's not the call to TextBox2.Select() that's the problem per se. This for instance, works fine for me
private void txt1_SelectionChanged(object sender, RoutedEventArgs e)
{
var start = TextBox1.SelectionStart;
var length = TextBox1.SelectionLength;
TextBox2.Select(3, 5);
}
unfortunately, using start and length versus the hard-coded 3 and 5, that is, the following, DOES NOT WORK:
private void txt1_SelectionChanged(object sender, RoutedEventArgs e)
{
var start = TextBox1.SelectionStart;
var length = TextBox1.SelectionLength;
TextBox2.Select(start, length);
}
I also discovered that I could select TWO characters if I started from the end, but only one from the beginning. That got me to thinking about dispatching the call to set the second selection:
private void txt1_SelectionChanged(object sender, RoutedEventArgs e)
{
var start = TextBox1.SelectionStart;
var length = TextBox1.SelectionLength;
Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low,
() => TextBox2.Select(start, length));
}
Now I can select 2 from the front and 3 and sometimes 4 from the back. Took it a step further, and was able to select as many as six or seven with a really fast swipe.
private void txt1_SelectionChanged(object sender, RoutedEventArgs e)
{
var start = TextBox1.SelectionStart;
var length = TextBox1.SelectionLength;
Dispatcher.RunIdleAsync((v) => Highlight());
}
public void Highlight()
{
TextBox2.Select(TextBox1.SelectionStart, TextBox1.SelectionLength);
}
Seems like the trick to working around this is not setting TextBox2 until whatever vestiges of the TextBox1 SelectionChanged event have completed.
This may be worth registering on Connect.
Mine is only a partial solution as well.
I did some debugging and noticed that the SelectionChanged event is fired throughout the text selection process. In other words, a single finger "swipe" will generate multiple SelectionChanged events.
As you found out, calling TextBox.Select during a text selection gesture affects the gesture itself. Windows seems to stop the gesture after the programmatic text selection.
My workaround is to delay as long as possible calling the TextBox.Select method. This does work well, except for one edge case. Where this method fails is in the following scenario:
The user begins a select gesture, say selecting x characters. The user, without taking their finger off the screen, pauses for a second or two. The user then attempts to select more characters.
My solution does not handle the last bit in the above paragraph. The touch selection after the pause does not actually select anything because my code will have called the TextBox.Select method.
Here is the actual code. As I mentioned above, there are multiple selection changed events fired during a single selection gesture. My code uses a timer along with a counter to only do the programmatic selection when there are no longer any pending touch generated selection changed events.
int _selectCounter = 0;
const int SELECT_TIMER_LENGTH = 500;
async private void TextBox1_SelectionChanged(object sender, RoutedEventArgs e)
{
// _selectCounter is the number of selection changed events that have fired.
// If you are really paranoid, you will want to make sure that if
// _selectCounter reaches MAX_INT, that you reset it to zero.
int mySelectCount = ++_selectCounter;
// start the timer and wait for it to finish
await Task.Delay(SELECT_TIMER_LENGTH);
// If equal (mySelectCount == _selectCounter),
// this means that NO select change events have fired
// during the delay call above. We only do the
// programmatic selection when this is the case.
// Feel free to adjust SELECT_TIMER_LENGTH to suit your needs.
if (mySelectCount == _selectCounter)
{
this.TextBox2.Select(this.TextBox1.SelectionStart, this.TextBox1.SelectionLength);
}
}

TextBox that Gets the value of another TextBox VISUAL C#

Is It possible that if I create two TextBoxes.
When the first TextBox is modified from input, the second text box is set to be read only and its value will update depending on what you had written in the first text box.
It's like when I am posting here in stackoverflow there is also a read only area that follows what I'm typing (The preview window). :)) Thanks!!!
If it's win-form application, it's so simple. try this :
private void txtFirstTextBox_TextChanged(object sender, EventArgs e) {
if (string.IsNullOrEmpty(txtFirstTextBox.Text)) {
txtSecondTextBox.Clear();
return;
}
txtSecondTextBox.Text = txtFirstTextBox.Text;
}
hope this help.
I should note: This is a solution if you're using WPF for your UI.
Yes that's easily possible if you have, for example the first textbox:
<TextBox x:Name="FirstBox"/>
You can bind to this text box's content via:
<TextBox x:Name"SecondBox" Text="{Binding ElementName="FirstBox", Path="Text", UpdateSourceTrigger=PropertyChanged}" IsEnabled="False"/>
And when the first text box changes, the second one should follow suit. This is all handled automatically for you via binding, it connects to the Text property on the TextBox named "FirstBox". This second TextBox is disabled by setting the IsEnabled property to "False"
Since there is already a WPF Solution and you didn't specify which you are using, I'll go ahead and post a WinForms solution.
Luckily, this is relatively simple in WinForms as well. You simply wire a TextChanged event handler for the first text box which updates the text of the second:
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox2.Text = ((TextBox)sender).Text;
}

Categories