Programmatically enable a disabled checkbox in a Windows Phone 7 app - c#

I'm writing my first device-specific application which is a Windows Phone 7 panorama app. I'm currently still busy on the UI as I'm playing around with the features then I stumbled upon a problem that I couldn't fix. You see, I have two checkboxes for some sort of login form. One is a "Remember me" and the other a "Sign me in automatically" checkbox. The action I want is that when I uncheck Remember Me, I would like the Sign in Automatically checkbox to be unchecked and disabled. That I was able to do but the reverse always causes an error. I used to write simple PHP web apps and JavaScript so I have some programming knowledge but C# is fairly new to me.
private void RememberMe_Unchecked(object sender, RoutedEventArgs e)
{
AutoSignIn.IsChecked = false;
AutoSignIn.IsEnabled = false;
}
That one works but this one doesn't:
private void RememberMe_Checked(object sender, RoutedEventArgs e)
{
AutoSignIn.IsEnabled = true;
}
The latter throws a "NullReferenceException was unhandled" error.
My XAML code looks like this:
<CheckBox Content="Remember me" Height="71" Name="RememberMe" Unchecked="RememberMe_Unchecked" Checked="RememberMe_Checked" IsEnabled="True" IsChecked="True" />
<CheckBox Content="Sign me in automatically" Height="71" Name="AutoSignIn" IsEnabled="True" IsChecked="True" />
I've done some research and my approach seem to be wrong but I'm not sure how to make it work.

Without the XAML I can't be 100% sure, but make sure you are not setting the IsChecked property programmatically. When you do so, the IsChecked method will get called once before everything is initialised properly on the page. So while the code posted by Matt works:
<CheckBox Name="AutoSignIn" />
<CheckBox Name="RememberMe" Checked="RememberMe_Checked" Unchecked="RememberMe_Unchecked" />
The following won't (because it tries to reference the AutoSignIn box before the page has finished initializing)
<CheckBox Name="AutoSignIn" />
<CheckBox Name="RememberMe" IsChecked="True" Checked="RememberMe_Checked" Unchecked="RememberMe_Unchecked" />
To fix this, you can set the IsChecked property programmatically instead of in XAML, or there might be some other way around this that someone else can point you to.

Your code works for me.
I used your event handlers with the following XAML:
<CheckBox Name="AutoSignIn" />
<CheckBox Name="RememberMe" Checked="RememberMe_Checked" Unchecked="RememberMe_Unchecked" />
Is the error thrown on the line in RememberMe_Checked? or on something else which is set as a consequence of changing the enabled state of AutoSignIn?
Do you, for instance, have any databindings that could be affecting this?

Related

Win Rt change event for TextBox

I have a screen that shows 2 collections.
On the left side, I display a list of sections. By default, the first section is selected. If you click on another section then that becomes selected instead.
On the right side, I have a list of associated questions for that section in a one to many relationships.
So each question belongs to a section and a section can have 1 to many questions.
Some questions are required to have an answer, and some are optionally answered.
To make it easy for the user to find the required questions, a red asterisk is displayed next to the answer textbox. When that question gets answered it disappears.
Also, I need to show an asterisk for each section where there are unanswered questions. Once they are all answered the asterisk for the section also disappears.
The visual tree is of this format;
SurveyPageViewModel - SurveyViewModel - SectionViewModel - QuestionViewModel
The code below shows the QuestionViewModel (which contains the answer property) and the XAML code is in a DataTemplate so I do not think there is a way up the Visual Tree to update the section.
So my (simplified) handler code for my answer property looks like this;
private string _answer;
public string Answer
{
get
{
return _answer;
}
set
{
if (SetProperty(ref _answer, value))
{
this.IfQuestionSetCheckIfAnswered(this.IsRequiredOnScreenAnswer);
}
}
}
private void IfQuestionSetCheckIfAnswered(bool value)
{
if (this.IsRequired && string.IsNullOrWhiteSpace(this.Text) == false)
{
this.EventAgg.GetEvent<RequiredAnswerUpdatedEvent>().Publish(value);
}
}
and my XAML for the question/answer;
<StackPanel Orientation="Horizontal" Grid.Row="1" Grid.ColumnSpan="2" Grid.Column="0" Margin="0, 0, 0, 5">
<TextBox Grid.Row="1"
Text="{Binding Path=Answer, Mode=TwoWay}"
MinWidth="300"
IsReadOnly="{Binding Path=IsReadOnly}" />
<TextBlock Text="*" FontSize="40" FontWeight="Bold"
Style="{StaticResource ResourceKey=RequiredSignal}" Margin="5, 0, 0, 0"
Visibility="{Binding Path=IsRequiredOnScreenAnswer, Converter={StaticResource ResourceKey=BooleanToVisibilityConverter}}" />
</StackPanel>
I am using Prism and the EventAggregator pattern to update the Selected Section which is in a different ViewModel.
Now this works except for one important issue. I only want to update the section once the page is loaded. Currently, this event is fired both when the page is loaded AND when the answer changes.
How do I get this to work so the load is ignored?
I only want to update the section once the page is loaded. Currently this event is fired both when the page is loaded AND when the answer changes.
I'd define a command to activate the update once the page is loaded
<interactivity:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="Loaded">
<core:InvokeCommandAction Command="{Binding ActivateCommand}" />
</core:EventTriggerBehavior>
</interactivity:Interaction.Behaviors>
The above requires the Behavior SDK on WinRT (or the NuGet package on UWP), alternatively you could handle the Loaded event in code behind and relay it to the ViewModel as well.
Then ActivateCommand is supposed to set a bool IsLoaded member of the ViewModel so that it can be tested within your IfQuestionSetCheckIfAnswered method.

Windows Phone page navigation does not work

I'm new in creating apps for Windows Phone. I've got problem with redirecting to another page. I've created blank page with HyperlinkButtonand in .cs file I wrote this:
private void but_elf_Click(object sender, RoutedEventArgs e)
{
this.Frame.Navigate(typeof(Elfy));
}
In xaml:
<HyperlinkButton x:Name="but_elf" Content="Elfy"
HorizontalAlignment="Center" Margin="100,125,100,255" Grid.Row="1"
VerticalAlignment="Center" Width="200" Height="70" />
When I launch app and click on the button - nothing happens. There are no errors, no messages. I've tried to put NavigateUri in button's property but after pressing button (in launched app) the message has shown: "You need to install an app for this task. Would you like to search for one in the Store?" After pressing "Yes" the app says: "Sorry, no apps found".
How to figure out this problem? I'm creating app for Windows Phone 8.1 in .NET Framework 4.5. Thanks for any help.
You are missing a reference for the 'Click'-event handler. Please change your XAML to this:
<HyperlinkButton x:Name="but_elf" Content="Elfy"
HorizontalAlignment="Center" Margin="100,125,100,255" Grid.Row="1"
VerticalAlignment="Center" Width="200" Height="70" Click="but_elf_Click" />
Please see:
C# Documentation for Click on MSDN
C# Documentation for HyperlinkButton on MSDN

WPF catch Click on a grid and all of his children labels, textboxs, etc.

Lets say I have a xaml file, a window, why not. in this xaml I have a grid with multiple labels, textBoxs, comboBoxs, lists... You see the patern. At a certain point (where X == true for say) I want to be able to catch a click inside the grid and everything in it.
I want to be still able to do what this click was going to do so a full-filled Rect over the grid is not the answer I'm looking for. The action of the click would be to put X back to false. nothing much.
Is there an easy way to manage a click on a grid and everything inside it?
Thanks in advance
You just need to use an event that is common to all of the controls. Probably the best one for this scenario is the UIElement.PreviewMouseDown event. Try this:
<StackPanel UIElement.PreviewMouseDown="StackPanel_PreviewMouseDown">
<Label Content="I'm a Label" />
<Button Content="I'm a Button" />
<CheckBox Content="I'm a CheckBox" />
</StackPanel>
You need to use one of the Preview... events so that you can catch it before the Buttons consume it... the UIElement.MouseDown event wouldn't work with Buttons for that very reason. However, you can use the othwer Preview... methods, like the UIElement.PreviewLeftMouseButtonDown event, for example.
Can you give your sample code?
From my understanding,you can use this,it will capture all your click inside grid.
.xaml
<Grid MouseDown="Grid_MouseDown">
<Label MouseDown="Grid_MouseDown" />
<Button MouseDown="Grid_MouseDown"/>
<Button MouseDown="Grid_MouseDown"/>
</Grid>
.xaml.cs
private Grid_MouseDown(object sender,MouseButtonEventArgs e)
{
if(X==true)
{
//doSomething
}
else
{
//do SomethingElse
}
}
edit: How about this?

Dynamically Adding child controls to a silverlight textbox

Please forgive this stupid question. (I'm originally an ASP.NET programmer.)
I'm trying to add a telerik context menu to a textbox control in the code behind.
Adding it in the xaml is very easy (this works)
<TextBox AcceptsReturn="True" Text="{Binding Mode=TwoWay, Path=Description}" TextWrapping="Wrap" x:Name="txtIssues" Width="280" Height="100" VerticalScrollBarVisibility="Auto">
<telerikNavigation:RadContextMenu.ContextMenu>
<telerikNavigation:RadContextMenu x:Name="contextMenu"
ItemClick="ContextMenuClick">
<telerikNavigation:RadMenuItem Header="Set Vista as Background" />
<telerikNavigation:RadMenuItem Header="Set Beach as Background" />
<telerikNavigation:RadMenuItem Header="Set Forest as Background" />
</telerikNavigation:RadContextMenu>
</telerikNavigation:RadContextMenu.ContextMenu>
</TextBox>
However I would like to completely add the the control from c# code and I can't find a why to add a control to a textbox. I've been looking for something like "txtIssues.Children.Add" but there doesn't seem to be an option.
First its best you understand that you are not adding a control to the TextBox. The RadContextMenu.ContextMenu is not a control it is an attached property.
Funnily enough the Telerik documentation describes adding a context menu to a textbox in C#. See Working with the RadContextMenu. Sometimes "RTM" is actually good advice.

TabControl- preventing user from changing the selected tab: MessageBox causing bug

I've been pounding away at this issue for a little while, and have only found part of the solution.
I'm trying to set up a TabControl so that I can in some cases prevent the user from changing the currently selected tab. When the user is prevented from changing the currently selected tab, then they are shown a dialog box.
I have already read the following documents:
WPF - reset ListBox scroll position when ItemsSource changes
http://wizardsofsmart.net/uncategorized/itemssourcechanged-event-using-attached-dependency-properties/
http://joshsmithonwpf.wordpress.com/2009/09/04/how-to-prevent-a-tabitem-from-being-selected/
http://social.expression.microsoft.com/Forums/en-US/wpf/thread/f7b46018-1e97-4bbe-ada8-49b75dbc1da2/
I have implemented the solution indicated in the 3rd link (though all of the above create the same error seen below). And it works, but...
Things mess up thoroughly if the user does the following:
attempts to change the tab when such an action is disallowed. The MessageBox pops up with the error.
the user clicks "OK" and is returned to the original window.
the user tries again to change the tab. No MessageBox appears.
if the user minimizes the window, and then maximizes it again, then the MessageBox that was supposed to appear earlier appears.
the user clicks "OK" and is returned to the original window... but the tab has been changed to the one they selected before, even though they should not be able to change tabs.
This is obviously not ideal behavior. Why isn't the MessageBox appearing the second time, and why is the tab changing when it should be disallowed from doing so?
If I remove the MessageBox part, it works fine.
Here is the code for the TabControl.SelectionChanged event handler:
bool _isChanging = false;
private void tabControlForNavigation_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (!_isChanging && canChangeTabs.IsChecked.HasValue)
{
_isChanging = true;
bool canLeave = canChangeTabs.IsChecked.Value; //normally this would be replaced by a check in the ViewModel
if (!canLeave)
{
int prevIndex = tabControlForNavigation.Items.IndexOf(tabControlForNavigation.SelectedContent);
tabControlForNavigation.SelectedIndex = prevIndex;
MessageBox.Show("Can't change tabs!"); //if I comment out this line, everything works fine.
}
_isChanging = false;
}
}
I am using MVVM to implement this. The Window looks like this:
<Window x:Class="TestTabControlSwitching.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
Height="350"
Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<CheckBox x:Name="canChangeTabs"
Content="Can Change Tabs"
IsChecked="True" />
<TabControl x:Name="tabControlForNavigation"
Grid.Row="1"
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding Collection}"
SelectedItem="{Binding SelectedItem}"
SelectionChanged="tabControlForNavigation_SelectionChanged"
Margin="4"
HorizontalAlignment="Stretch">
<TabControl.ItemTemplate>
<DataTemplate>
<ContentPresenter Content="{Binding Path=Name}" />
</DataTemplate>
</TabControl.ItemTemplate>
</TabControl>
</Grid>
I'm omitting the rest of the code for sake of brevity- there is a pretty straight-forward ViewModel structure backing the window.
As you noticed, the problem is the MessageBox inside the event handler. The focus will change to the MessageBox and you can get all kind of undesired effects. I've had my own problems with this.
Here is a couple of SO question on the same subject
WPF: Does MessageBox Break PreviewMouseDown?
Wpf stop routing event when MessageBox appear?
If you must display a message to the user then an alternate approach might be to create a new Window which you style like a MessageBox and then call Show (not ShowDialog) on it inside the event handler.
I know this post is a bit old, but I have a very easy way to accomplish this:
Use the tab_Enter event and create a method that performs your check and displays a MessageBox to the user and then set myTabs.SelectedIndex to the prior index. A simple example:
private void someTab_Enter(object sender, EventArgs e)
{
if (myCondition)
{
MessageBox.Show("Sorry, myCondition will not let you move to this tab.");
myTabs.SelectedIndex = someOtherTabIndex;
}
}
This was a very detailed question. I had the same problem you had (i.e. the message box doesn't display on 2nd or 3rd selection changed until you minimize and maximize the window) and after much debugging and multiple google searches, stumbled on the below linked MSDN forum post.
[TabControl SelectionChanged Strange Behaviour?]
Please ignore the poorly formatted question and answer. But as mentioned in the answer, putting it inside a dispatcher and focussing the selected tab after setting the index resolved the issue for me.
You are missing an easy trick. Just make focusable=False for the Tab header.
<TabItem Header="MY TAB" Focusable="False">
You could bind this property to your view model.
<TabItem Header="MY TAB" Focusable="{Binding Bool_CanHasCheeseBurger}">

Categories

Resources