I have picture repo, foreach picture i want a radiobutton in my wrappanel. I want to connect all of these radiobuttons to an event, so when one is checked, all the properties of the pictures shows up on screen.
Problem is for some reason i cannot access the events members of radiobutton when creating them.
I've tried google, couldnt find same problem
public void UpdatePictures(PictureRepo pictureRepo)
{
foreach (var picture in pictureRepo.RepoCollection)
{
WP_mainWrapPanel.Children.Add(new RadioButton
{
Margin = new Thickness(2, 10, 2, 10),
Height = 100,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Top,
Content = new Image { Source = new BitmapImage(new Uri(picture.PictureLink, UriKind.Relative)) },
Name = picture.Name.ToString(),
});
}
}
Radiobuttons have an event for if the button is checked, i cannot access it for some reason.
Try this:
private void SetupRadioButton()
{
RadioButton radio1 = new RadioButton
{
Text = "Your Properties Here",
};
radio1.CheckedChanged += Radio1_CheckedChanged;
}
private void Radio1_CheckedChanged(object sender, EventArgs e)
{
throw new NotImplementedException();
}
You need to create your button, and keep a reference to it.Then you can add the event handler.
var btn = new RadioButton
{
Margin = new Thickness(2, 10, 2, 10),
Height = 100,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Top,
Content = new Image { Source = new BitmapImage(new Uri(picture.PictureLink, UriKind.Relative)) },
Name = picture.Name.ToString(),
};
WP_mainWrapPanel.Children.Add(btn);
btn.Checked += btn_Checked;
The event definition looks something like this
private static void btn_Checked(object sender, RoutedEventArgs e)
{
//do stuff
}
Related
I'm practicing my coding and am trying to create a till by Dynamically prefill the items that are stored in a text file. I can dynamically create Tabs, Buttons and create menu buttons based on the categories of items. Where I'm struggling is I'm trying to switch the Tab on a button click. The Tabs are given a Name, which is the category ID, and the Text displays the category. In the event that trys to switch the tab I get the following error:
Error CS0266 Cannot implicitly convert type 'object' to 'System.Windows.Forms.TabPage'. An explicit conversion exists (are you missing a cast?)
I'm presuming that I need to Create a tab page or something, but I can't find out how to do this. Been on it for hours! Here's my code....
public partial class Form1 : Form
{
private void Form1_Load(object sender, EventArgs e)
{
string[] loadedFile = File.ReadAllLines(#"h:\shopItemsV2.txt");
foreach (string line in loadedFile)
{
// Split string and create required variables
string[] newBtnData = line.Split(',');
int catID = int.Parse(newBtnData[0]);
string cat = newBtnData[1];
string item = newBtnData[2];
double price = double.Parse(newBtnData[3]);
// Create tab if needed
if (tabControl1.TabCount < catID)
{
TabPage tp = new TabPage()
{
Text = cat,
Name = catID.ToString()
};
tabControl1.TabPages.Add(tp);
// Add FlowLayoutPanel with unique name
FlowLayoutPanel fp = new FlowLayoutPanel()
{
Name = "fp" + catID.ToString(),
Dock = DockStyle.Fill
};
// Add FlowLayoutPanel to correct Tab
tabControl1.TabPages[catID-1].Controls.Add(fp);
// Create Button for menu
Button newMenuBtn = new Button()
{
Name = cat + "Btn",
Tag = catID,
Width = 100,
Height = 50,
Text = cat,
};
newMenuBtn.Click += SwitchTab;
menuFP.Controls.Add(newMenuBtn);
}
// Create Button
Button newBtn = new Button()
{
Name = item,
Tag = price,
Width = 100,
Height = 100,
Text = item,
};
newBtn.Click += AddItem;
//Add button to correct tab
foreach (TabPage tabP in tabControl1.TabPages)
{
if (tabP.Name == catID.ToString())
{
Control fp = this.Controls.Find("fp"+catID, true).First();
fp.Controls.Add(newBtn);
}
}
}
}
private void SwitchTab(object sender, EventArgs e)
{
// Create button, switch to required Tab
// Tabs named the same as Tag on the button
Button clickedBtn = sender as Button;
tabControl1.SelectedTab = clickedBtn.Tag;
}
}
Any help would be greatly appreciated.
You can store anything in the Tag() property of your button. With that in mind, store a reference to your TabPage!
Change:
// Create Button for menu
Button newMenuBtn = new Button()
{
Name = cat + "Btn",
Tag = catID,
Width = 100,
Height = 50,
Text = cat,
};
To:
// Create Button for menu
Button newMenuBtn = new Button()
{
Name = cat + "Btn",
Tag = tp; // store the reference to the TabPage you created
Width = 100,
Height = 50,
Text = cat,
};
Then the suggestion by Uwe Keim should work:
tabControl1.SelectedTab = clickedBtn.Tag as TabPage;
private void AddNewPr_Click(object sender, EventArgs e)
{
TabPage tab = new TabPage();
_list = new ListBox();
_list2 = new ListBox();
PictureBox picBox = new PictureBox();
picBox.Click = picBox_Click;
//More stuff here
//Add the controls
tabControl1.Controls.Add(tab);
tab.Controls.Add(list);
tab.Controls.Add(list2);
tab.Controls.Add(pictureBox);
}
Actual screenshot of the problem
See the attached image here, I have 4 buttons in a gird when any of them are clicked they show me a webview, but for some reason I am unable to expand the web view so that it covers rest of the screen. As you can see in the picture , webview is in a single column and buttons are in 1 row. I would really appreciate help. Thanks.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace LocalDataAccess
{
public partial class RecipeSites : ContentPage
{
public RecipeSites()
{
this.Content = gridlayout();
}
public Grid gridlayout()
{
BackgroundColor = Color.White;
Button allrecipes = new Button
{
BackgroundColor = Color.Transparent,
};
allrecipes.Clicked += new EventHandler(allrecipes_Click);
allrecipes.Image = "alrecipe.png";
Button delia = new Button
{
BackgroundColor = Color.Transparent,
};
delia.Clicked += new EventHandler(delia_Click);
delia.Image = "delia.gif";
Button bbc = new Button
{
BackgroundColor = Color.Transparent,
};
bbc.Clicked += new EventHandler(bbc_Click);
bbc.Image = "bbc.jpg";
Button food = new Button
{
BackgroundColor = Color.Transparent,
};
food.Clicked += new EventHandler(food_Click);
food.Image = "food.jpg";
var grid = new Grid();
RowDefinition gridRow1 = new RowDefinition();
gridRow1.Height = new GridLength(7, GridUnitType.Star);
grid.RowDefinitions.Add(gridRow1);
grid.Children.Add(allrecipes, 0, 1);
grid.Children.Add(delia, 1, 1);
grid.Children.Add(bbc, 2, 1);
grid.Children.Add(food, 3, 1);
return grid;
}
public void food_Click(object sender, EventArgs e)
{
Grid sl = gridlayout();
WebView webView = new WebView
{
Source = new UrlWebViewSource
{
Url = " http://www.food.com/",
},
VerticalOptions = LayoutOptions.FillAndExpand,
};
var grid1 = new Grid()
{ VerticalOptions = LayoutOptions.FillAndExpand };
ColumnDefinition c2 = new ColumnDefinition();
c2.Width = new GridLength(10, GridUnitType.Star);
grid1.ColumnDefinitions.Add(c2);
grid1.Children.Add(webView, 3,1 );
this.Content = sl;
}
public void allrecipes_Click(object sender, EventArgs e)
{
Grid sl = gridlayout();
WebView webView = new WebView
{
Source = new UrlWebViewSource
{
Url = "http://allrecipes.co.uk/",
},
HorizontalOptions = LayoutOptions.FillAndExpand
};
sl.Children.Add(webView);
this.Content = sl;
}
public void delia_Click(object sender, EventArgs e)
{
Grid sl = gridlayout();
WebView webView = new WebView
{
Source = new UrlWebViewSource
{
Url = "http://www.deliaonline.com/recipes",
},
VerticalOptions = LayoutOptions.FillAndExpand
};
sl.Children.Add(webView);
this.Content = sl;
}
public void bbc_Click(object sender, EventArgs e)
{
Grid sl = gridlayout();
WebView webView = new WebView
{
Source = new UrlWebViewSource
{
Url = "http://www.bbc.co.uk/food/recipes/",
},
VerticalOptions = LayoutOptions.FillAndExpand
};
sl.Children.Add(webView);
this.Content = sl;
}
}
}
you need to set a span value if you want a control to go across multiple rows or columns
// add button to col 0 row 4
controlGrid.Children.Add (zeroButton, 0, 4);
// make the button span 2 columns
Grid.SetColumnSpan (zeroButton, 2);
I am using Xamarin.Forms to add custom render to a button. I need to add a click event on CmButton without creating reference variable, or defining outside of the StackLayout.
Here is my code:
Content = new StackLayout
{
Children
{
new CmButton
{
Text = "SIGN UP| AGREE TO TERMS",
BackgroundColor = Color.Transparent,
BorderColor = Color.Transparent,
BorderWidth = 0,
TextColor = Color.White
}
}
}
I want click event within the new Button{} block
Use Command instead of Click
var btn = new Button
{
Text = "",
Command = new Command(()=>
{
})
};
Use-
Button.Clicked += OnButtonClicked;
It will create a click event of button as-
void OnButtonClicked(object sender, EventArgs e)
{
}
For more detail:- https://channel9.msdn.com/Shows/Visual-Studio-Toolbox/VS-Toolbox-Xamarin-Forms
and https://developer.xamarin.com/guides/xamarin-forms/xaml/xaml-basics/getting_started_with_xaml/
You have to assign your button to a variable to use events.
myButton = new CmButton
{
Text = "SIGN UP| AGREE TO TERMS",
BackgroundColor = Color.Transparent,
BorderColor = Color.Transparent,
BorderWidth = 0,
TextColor = Color.White
}
Content = new StackLayout
{
Children
{
myButton
}
}
myButton.Clicked += (o, e) => {
//click event handler
};
How can I add Swipe to delete in my note list app.I am using xamarin forms. I have searched in xamarin forms samples but could not find it. I also tried the list view performance options with menuItem etc but I dont know how to adjust that in my code. Can anyone help me with this please?
My code is as follows:
public partial class MyPage
{
List<Note> notes;
string NotesFile {
get {
var documents = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
return System.IO.Path.Combine (documents, "notes.json");
}
}
public MyPage()
{
BuildContent();
LoadNotes ();
ReloadListContents ();
AddNoteButton.Clicked += (sender, args) => {
var note = new Note("typ...");
notes.Add(note);
EditNote(note);
};
NoteListView.ItemTapped += (sender, row) =>
{
NoteListView.SelectedItem = null;
Note note = (Note)row.Item;
EditNote(note);
};
buttonDelete.Clicked += (sender, args) =>{
notes.RemoveAt(0);
DisplayAlert("Delete", "Row deleted", "OK");
};
}
}
MyPage.cs
{
public ListView NoteListView = new ListView ();
public Button AddNoteButton;
public Button buttonDelete;
private void BuildContent()
{
AddNoteButton = new Button
{
Text = "Add New Note",
TextColor = Color.White,
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center
};
buttonDelete = new Button
{
Text = "Delete Note ",
TextColor = Color.White,
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center
};
Content = new StackLayout
{
BackgroundColor = Color.Black,
Children = {
new Label {
Text = "Note Taker",
TextColor = Color.White
},
NoteListView,
AddNoteButton,
buttonDelete
}
};
}
Im responding to this question in CS code rather than XAML (My Preferred) if anyone would like the Xaml response please drop a comment below and I'll write the XAML alongside the CS.
So to complete what you have asked in Xamarin.Forms on ListView elements you must first create the ViewCell that you would like to display the data in each cell in the ListView and give it context actions. Here is an example:
public class CustomViewCell : ViewCell
{
public CustomViewCell()
{
//instantiate each element we want to use.
var image = new CircleCachedImage
{
Margin = new Thickness(20, 10, 0, 10),
WidthRequest = App.ScreenWidth * 0.15,
HeightRequest = App.ScreenWidth * 0.15,
Aspect = Aspect.AspectFill,
BorderColor = Color.FromHex(App.PrimaryColor),
BorderThickness = 2,
HorizontalOptions = LayoutOptions.Center
};
var nameLabel = new Label
{
Margin = new Thickness(20, 15, 0, 0),
FontFamily = "Lato",
FontAttributes = FontAttributes.Bold,
FontSize = 17
};
var locationLabel = new Label
{
Margin = new Thickness(20, 0, 0, 5),
FontFamily = "Lato",
FontSize = 13
};
//Create layout
var verticaLayout = new StackLayout();
var horizontalLayout = new StackLayout() { BackgroundColor = Color.White };
//set bindings
nameLabel.SetBinding(Label.TextProperty, new Binding("Name"));
locationLabel.SetBinding(Label.TextProperty, new Binding("Location"));
image.SetBinding(CircleCachedImage.SourceProperty, new Binding("Image"));
//Set properties for desired design
horizontalLayout.Orientation = StackOrientation.Horizontal;
horizontalLayout.HorizontalOptions = LayoutOptions.Fill;
image.HorizontalOptions = LayoutOptions.End;
//add views to the view hierarchy
horizontalLayout.Children.Add(image);
verticaLayout.Children.Add(nameLabel);
verticaLayout.Children.Add(locationLabel);
horizontalLayout.Children.Add(verticaLayout);
//HERE IS THE MOST IMPORTANT PART
var deleteAction = new MenuItem { Text = "Delete", IsDestructive = true }; // red background
deleteAction.Clicked += async (sender, e) => {
//Here do your deleting / calling to WebAPIs
//Now remove the item from the list. You can do this by sending an event using messaging center looks like:
//MessagingCenter.Send<TSender,string>(TSender sender, string message, string indexOfItemInListview)
};
// add to the ViewCell's ContextActions property
ContextActions.Add(deleteAction);
// add to parent view
View = horizontalLayout;
}
}
Now you must do the following to your ListView:
listView = new ListView();
lstView.ItemTemplate = new DataTemplate(typeof(CustomViewCell));
In the same Content Page that you have the ListView you must also subscirbe to the MessagingCenter listening to the same parameters as set in the custom view cell as above. Please read the link provided if you have not used the MessagingCenter before. Inside of this method you must then remove the item from the listview with the index sent to this method.
If anyone needs any further explanations drop a comment below and Ill edit this post.
So for this assignment in class I'm making a richtextbox editor in C# winforms, in this assignment I have to include a find function, but I can't seem to get the hang of it
EDIT: it closes every time I click the search button, but that's not what I want, I want it to close when the user closes the actual dialog via the X in the top right, the search button should just highlight the found string by using the .Find() method
Here's my code up until now:
private void zoekenToolStripMenuItem_Click(object sender, EventArgs e)
{
string searchValue = SearchDialog();
Search(searchValue);
}
public string SearchDialog()
{
Form findDialog = new Form();
findDialog.Width = 500;
findDialog.Height = 142;
findDialog.Text = "Zoeken";
Label textLabel = new Label() { Left = 10, Top = 20, Text = "Zoek naar:", Width = 100 };
TextBox inputBox = new TextBox() { Left = 150, Top = 20, Width = 300};
Button search = new Button() { Text = "Zoek", Left = 350, Width = 100, Top = 70 };
search.Click += (object sender, EventArgs e) => { findDialog.Close(); };
findDialog.Controls.Add(search);
findDialog.Controls.Add(textLabel);
findDialog.Controls.Add(inputBox);
findDialog.ShowDialog();
return (string)inputBox.Text;
}
void Search(string searchValue)
{
rtxtInhoud.Find(searchValue);
}
The part:
search.Click += (object sender, EventArgs e) => { findDialog.Close(); };
is what I'm really stuck on
Thanks in advance
EDIT: here's something that I tried to do, which didn't work
public string SearchDialog()
{
Form findDialog = new Form();
findDialog.Width = 500;
findDialog.Height = 142;
findDialog.Text = "Zoeken";
Label textLabel = new Label() { Left = 10, Top = 20, Text = "Zoek naar:", Width = 100 };
TextBox inputBox = new TextBox() { Left = 150, Top = 20, Width = 300};
Button search = new Button() { Text = "Zoek", Left = 350, Width = 100, Top = 70 };
Button findNext = new Button() { Text = "Volgende", Left 250, Width = 100, Top = 70};
search.Click += (object sender, EventArgs e) => { rtxtInhoud.Find(inputBox.Text); };
findDialog.Controls.Add(search);
findDialog.Controls.Add(textLabel);
findDialog.Controls.Add(inputBox);
findDialog.ShowDialog();
return (string)inputBox.Text;
}
This waits for the Dialog to be closed before highlighting the found string. Which is NOT what I want, I want it to keep the Dialog open, but still highlight the text
it closes every time I click the search button
Yes, that's because you added an event handler to the search button that closes the form:
search.Click += (object sender, EventArgs e) => { findDialog.Close(); };
but that's not what I want, I want it to [...]
Then write the code in that handler such that it does what you actually want it to do, instead of having it close the form.
In your main form code, create a method that searches your text and highlights a found string. Then hook this method up to your search dialog button like the sample below. Also, I think you should call form.Show() instead of .ShowDialog(), so the other form can respond to input.
private void HighlightString(string stringToHighlight)
{
// Code here to search your text and highlight a string.
}
private void SearchDialog()
{
var findDialog = new Form {Width = 500, Height = 142, Text = "Zoeken"};
var textLabel = new Label() {Left = 10, Top = 20, Text = "Zoek naar:", Width = 100};
var inputBox = new TextBox() {Left = 150, Top = 20, Width = 300};
var search = new Button() {Text = "Zoek", Left = 350, Width = 100, Top = 70};
search.Click += (object sender, EventArgs e) => HighlightString(inputBox.Text);
findDialog.Controls.Add(search);
findDialog.Controls.Add(textLabel);
findDialog.Controls.Add(inputBox);
findDialog.Show();
}
Use this code:
Application.Exit();