I am trying to create a Trivia App. I have some very basic Xamarin Form code implementing a Radio Button. The buttons work fine (ie a selection is registered and processed properly). The issue is that after the first question is answered, the radio button selection persists when the second question is displayed. Is there a way to reset the radio buttons between questions so that they are all not selected?
Here is the basic xaml code and the code behind:
Xaml:
<StackLayout Margin="20">
<RadioButton x:Name="Option0" CheckedChanged="RadioButton_CheckedChanged" IsTabStop="False" IsChecked="False"></RadioButton>
<RadioButton x:Name="Option1" CheckedChanged="RadioButton_CheckedChanged" IsTabStop="False" IsChecked="False"></RadioButton>
<RadioButton x:Name="Option2" CheckedChanged="RadioButton_CheckedChanged" IsTabStop="False" IsChecked="False"></RadioButton>
<RadioButton x:Name="Option3" CheckedChanged="RadioButton_CheckedChanged" IsTabStop="False" IsChecked="False"></RadioButton>
</StackLayout>
Code behind: (Note: getQuestion() has the logic to display the next question so I have not included it here and I suspect something needs to be done at // do something to reset the radio button but I am not sure what to do)
void RadioButton_CheckedChanged(System.Object sender, Xamarin.Forms.CheckedChangedEventArgs e) // sender is of class System.Object and must be converted in the proper type
{
Debug.WriteLine("\nRadio Button Clicked");
Debug.WriteLine("sender: " + sender);
Debug.WriteLine("e: " + e);
var s = sender;
var radioEvent = e;
// converts sender to Radio Button type
var radioButton = (RadioButton)sender;
// Once in Radio Button type now you can see and use content
string contentString = radioButton.Content.ToString();
Debug.WriteLine("contentString: " + contentString);
if (radioButton.IsChecked == true)
{
if (contentString == Movie.Text)
{
DisplayAlert("Correct", "You're Good!", "OK");
Debug.WriteLine("Correct Answer");
ans_correct = ans_correct + 1;
// do something to reset the radio button
getQuestion();
}
else
{
DisplayAlert("Whoops", "Wrong Agian!", "OK");
Debug.WriteLine("Wrong Answer");
ans_wrong = ans_wrong + 1;
}
}
}
Never mind - I guess I just had to post the question to find the answer.
It turns out all I needed to do was put
radioButton.IsChecked = false;
where I had my comment
// do something to reset the radio button
Related
i have a page where user can swap labels. So I have a ExtendedWebView CZ and ExtendedWebView EN once user presses button i need them to swap. I have decided to swap these ExtendedWebView in the bac of my page as that seemed much easier however both these commes with button that each fires different pop up. So if i swap ExtendedWebView CZ i need the button that fires CZ pop up to be swapped also.
This is how i am changing my ExtendedWebViews
bool isSwap = false;
private void ChangePosition(object sender, EventArgs e)
{
isSwap = !isSwap;
czView.RemoveBinding(ExtendedWebView.SourceProperty);
enView.RemoveBinding(ExtendedWebView.SourceProperty);
if (isSwap)
{
btnChangePositions.Text = "EN/CZ";
czView.SetBinding(ExtendedWebView.SourceProperty,("EN"));
enView.SetBinding(ExtendedWebView.SourceProperty, ("CZ"));
}
else
{
btnChangePositions.Text = "CZ/EN";
czView.SetBinding(ExtendedWebView.SourceProperty, ("CZ"));
enView.SetBinding(ExtendedWebView.SourceProperty, ("EN"));
}
}
Xaml
<Label
x:Name="makeLargerEN"
FontFamily="{StaticResource IconsFontFamily}"
HorizontalTextAlignment="End"
Text="{Binding MakeLargerEN}"
TextColor="{DynamicResource AccentColor}"
VerticalTextAlignment="End">
<Label.GestureRecognizers>
<TapGestureRecognizer Command="{Binding MakeWebViewLargeEnCommand}" />
</Label>
And this is my pop up in the vIew Model
private async void MakeWebViewLargeEN()
{
var popup = new WordAndPhrasePopup(htmlSourceName.Html);
await PopupNavigation.Instance.PushAsync(popup);
}
I have tried in back of the content page
makeLargerEN.SetBinding(Label.TextProperty, "MakeLargerEN");
Just to swap labels but then the right command doesnt get fired
I have tried this, but gesture doesnt have Command or CommandProperty
makeLargerCZ.SetBinding(GestureRecognizer.Command, new Binding("MakeLargerEN"));
I am doing it in the back of COntent page because i am setting up there another swap that goes along with this one.
You could remove and add GestureRecognize in code behind .
Remove
makeLargerEN.GestureRecognizers.Clear();
Add
makeLargerEN.GestureRecognizers.Add(new TapGestureRecognizer
{
NumberOfTapsRequired = 1,
Command = new Command(() =>
{
//...
}),
});
Iam using syncfusion SFListview in my xamarin forms app. I implemented multiselect of listview cell from https://help.syncfusion.com/xamarin/sflistview/selection?cs-save-lang=1&cs-lang=xaml.It works fine.But the problem iam facing is everytime we need to hold the itemcell for selection. Is it possible for multiselect that hold only for first cell and tap for all other cell?
Is it possible for multiselect that hold only for first cell and tap for all other cell?
Sure can do that.If you want multiselect items,I guess that next steps will do some tasks about multiselect items.The picture below may look like the one you want.
You can look at the content of this chapter in the share link, and the sample code it provides.
Solution One:(Generally acceptable)
If the project doesn't mind adding a control button outside, then this will be the quickest and easiest way.That is to add a ToolbarItems in the NavigationPage, use it to control whether you can click multiple selections without jumping to the next page.
Add ToolbarItems :
<ContentPage.ToolbarItems>
<ToolbarItem x:Name="ToolbarItemsButton" Text="MultipleSelect" Clicked="Edit_Clicked"/>
</ContentPage.ToolbarItems>
<sync:SfListView x:Name="listView"
SelectionGesture="Hold"
SelectionMode="Multiple"
ItemTapped="ListView_ItemTapped"
SelectionBackgroundColor="Transparent"
IsStickyHeader="True" ItemSize="70">
...
In ContentPage ,add Flag to judge SelectionMode of ListView.
int flag = 0;
private void Edit_Clicked(object sender, EventArgs e)
{
if(0 == flag)
{
listView.SelectionGesture = TouchGesture.Tap;
ToolbarItemsButton.Text = "Done";
flag = 1;
}
else
{
ToolbarItemsButton.Text = "MultipleSelect";
listView.SelectionGesture = TouchGesture.Hold;
flag = 0;
}
}
Can judge when you can switch to the next page.
private void ListView_ItemTapped(object sender, Syncfusion.ListView.XForms.ItemTappedEventArgs e)
{
if(0 == flag)
{
Navigation.PushAsync(new ContentPage());
}
}
Solution Two:(Recommended)
SfListView has a method is ItemHolding.Not using another button also can exchange the SelectionMode.
Xaml code different is adding this method of SfListView.
<sync:SfListView x:Name="listView"
SelectionGesture="Hold"
SelectionMode="Multiple"
ItemTapped="ListView_ItemTapped"
SelectionBackgroundColor="Transparent"
ItemHolding="ListView_ItemHolding" // ItemHolding
IsStickyHeader="True" ItemSize="70">
When OnHolding can do something here:
private void ListView_ItemHolding(object sender, ItemHoldingEventArgs e)
{
if (0 == flag)
{
listView.SelectionGesture = TouchGesture.Tap;
ToolbarItemsButton.Text = "Done";
flag = 1;
}
else
{
listView.SelectionGesture = TouchGesture.Hold;
ToolbarItemsButton.Text = "MultipleSelect";
flag = 0;
}
}
Judge when you can switch to the next page.
private void ListView_ItemTapped(object sender, Syncfusion.ListView.XForms.ItemTappedEventArgs e)
{
if(0 == flag)
{
Navigation.PushAsync(new ContentPage());
}
}
Solution Three:(Not recommended here)
Generally, for the multiple selection of the cell of the listview, we will process the template of the custom cell, such as adding a button in the template. When clicking, the item can be marked as selected, and the UI of the item can also be customized as The style when selected.
I want my button color to change when xbox select box is on the button. How can I achieve that? I haven't got an event on focus in Xbox UWP app.
you need a GotFocus and LostFocus events on that button you are trying to do this.
<Button x:Name="MyButton" GotFocus="ButtonGotFocus" LostFocus="ButtonLostFocus"/>
and in the code behind you can change the background color accordingly. you can also optionally check the DeviceFamily first if you want the behavior only on xbox.
private void GotFocus(object sender, object args)
{
if(AnalyticsVersionInfo.DeviceFamily == "Windows.Xbox")
{
//change the color when the button gets focus
MyButton.BackgroundColor = new SolidColorBrush(Colors.Blue);
}
}
private void LostFocus(object sender, object args)
{
if(AnalyticsVersionInfo.DeviceFamily == "Windows.Xbox")
{
//change the color when the button looses focus
MyButton.BackgroundColor = new SolidColorBrush(Colors.Green);
}
}
more on DeviceFamily property : https://learn.microsoft.com/en-us/uwp/api/windows.system.profile.analyticsversioninfo.devicefamily#Windows_System_Profile_AnalyticsVersionInfo_DeviceFamily
Update
if you want same effect on all or multiple buttons, just assign the events on every button you want the affect on like so :
<Button x:Name="MyButton" GotFocus="ButtonGotFocus" LostFocus="ButtonLostFocus"/>
<Button x:Name="MyButton2" GotFocus="ButtonGotFocus" LostFocus="ButtonLostFocus"/>
and in the backend just replce MyButton with (sender as Button)
(sender as Button).BackgroundColor = new SolidColorBrush(Colors.Green);
Truncate the label text makes it one line. App shows description, it needs to be displayed in 2-3 lines but Xamarin "LineBreakMode=TailTruncation" truncates it and restricts it to one line.
Is there any way to truncate label text and show in multi-lines. If text doesn't fit into n number of lines, then it should be truncated.
<Label LineBreakMode="TailTruncation" FontSize = "20" Text="Multi line Text" />
Thanks.
Since Xamarin.Forms 3.3 a new property was introduced for this feature. It's called MaxLines.
Here is an example in C#:
var yourLabel = new Label
{
LineBreakMode = LineBreakMode.TailTruncation,
Text = "Your text",
MaxLines = 2
};
Here is an example in XAML:
<Label
LineBreakMode="TailTruncation"
Text="Your text"
MaxLines="2" />
See https://learn.microsoft.com/de-de/dotnet/api/xamarin.forms.label.maxlines?view=xamarin-forms for more information.
I have implemented custom renderer to handle this.
http://depblog.weblogs.us/2016/06/27/xamarin-forms-multi-line-label-custom-renderer-gotcha/
//Droid
public class MultiLineLabelRenderer : LabelRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs e)
{
base.OnElementChanged(e);
if (Control != null)
{
Control.LayoutChange += (s, args) =>
{
Control.Ellipsize = TextUtils.TruncateAt.End;
Control.SetMaxLines(2);
}
};
}
}
I've got a web app in ASP.NET 2.0 in which I need to have a highly customized grid. One of the columns in the grid contains a radio button for each row.
I'm implementing it as a Repeater control, with a div in each ItemTemplate. The problem is that the radio buttons (ASP:RadioButton tags) are not being grouped like they should; selecting one of them doesn't deselect the rest. I've set the GroupName property on them already, but I don't see that being rendered in the HTML anywhere via Firebug. A google search tells me that the "name" attribute on <input type='radio> is what determines its group membership, but ASP is using that already as some kind of unique identifier. Each radio button looks something like this when rendered to HTML:
<input id="{asp_garbage_naming}_ctl01_rbFoo" type="radio"
name="ctl03$controlName$otherControlName$ctl01$name"
value="rbHost" checked="checked" />
Is there a way to make this work? Or am I going to have to provide radio button behavior on my own (javascript, etc)?
A coworker ran across this issue and implemented a jQuery solution. Here's an excerpt of it:
That gave me the radio button functionality that I wanted, but it prevented me from getting the selected radio button on postback. So I decided to just implement the radio button functionality manually.
var radios = $("input:radio");
radios.click(function() {
radios.removeAttr('checked');
$(this).attr('checked', 'checked');
return true;
});
Which gave me the correct functionality and I could still get the selected radio button and textbox on postback. Probably not the most elegant solution, but I couldn’t find any other way to do it.
Full post: Radio button within a repeater problem
In the server side do as follows:
protected void rptRepeaterName_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
RadioButton rdbRadioButtonName = e.Item.FindControl("rdbRadioButtonName") as RadioButton;
Repeater rptRepeaterName = sender as Repeater;
rdbRadioButtonName.Attributes.Add("onclick", string.Format("return radioSelected('{0}', '{1}')", rptRepeaterName.ClientID, rdbRadioButtonName.ClientID));
}
In the javascript do as follows
function radioSelected(rptpricelevel, rdbPriceLevel)
{
for (cnt = 0; cnt<100; cnt++)
{
var rdbId = rptpricelevel;
if(cnt < 10)
{
rdbId = + '_ctl0' + cnt + '_rdbRadioButtonName';
}
else
{
rdbId = + '_ctl' + cnt + '_rdbRadioButtonName';
}
var rdb = document.getElementById(rdbId);
if(rdb != null)
{
if(rdbId != rdbPriceLevel)
{
rdb.checked = false;
}
}
}
}
Question? Do you need these radio buttons to be server controls (i.e. do you need the runat=server tag)? If not, you could simply have regular html radio buttons on the column and bind any properties to it using the <%#Eval("Property")%> syntax. Just a thought