c# wpf button with variable as name? same colours in all buttons - c#

Hello I have 2 questions.
This is my code: (kolLos make random number between 0 and 255)
public int numer_prostokata = 1;
private void Glowny_przycisk_Click(object sender, RoutedEventArgs e)
{
// Create a Button
Button blueRectangle = new Button();
blueRectangle.Content = numer_prostokata;
var nazwa_batona = "s_b_" + numer_prostokata;
blueRectangle.Name = nazwa_batona;
MainWindow.Children.Add(blueRectangle);
myColor.Color = Color.FromArgb(kolLos(), kolLos(), kolLos(), kolLos());
blueRectangle.Background = myColor;
numer_prostokata++;
}
It almost work. Buttons are generating on click. They have different Contents, but... always the same color. Colors are changing after each Click, but all buttons have the same (for example all red or all blue)...
What I did wrong?
And second question:
name of Buttons is "s_b_" + number. It is in var "nazwa_batona". But when I use
nazwa_batona.Background = myColor;
it doesn't work... What should I do?
I'm very begining in C#... I googled and searched many hours but didn't find answers...
Oh! There can be many buttons created and they can be in different places...

I'm assuming myColor is some class level SolidColorBrush since it isn't declared in the function. Given that, the following code simply changes the color of that brush, then assigns the brush to the new button instance:
myColor.Color = Color.FromArgb(kolLos(), kolLos(), kolLos(), kolLos());
blueRectangle.Background = myColor;
However, every button has the same brush instance, so when you change the color for the next button, all the previous ones change as well.
You need to create a new brush:
SolidColorBrush backgorundBrush = new SolidColorBrush();
backgorundBrush.Color = Color.FromArgb(kolLos(), kolLos(), kolLos(), kolLos());
blueRectangle.Background = backgorundBrush;

Related

XAML WPF -Why the background image of button does not change?

I am new to XAML, and I am trying to change the background image of buttons.
So, the original background image is heart.jpg.
I wrote function changeHearts() that suppose to check if the background image is: skull.png ,
So it will change the image of the button to: heart.jpg .
The problem is that when I call the function, it does not change the image of the buttons.
Both of the 2 images property is set to: resource.
*Function in my c# code:
private void changeHearts()
{
Uri resourceUri = new Uri("/Images/skull.png", UriKind.Relative);
StreamResourceInfo streamInfo = Application.GetResourceStream(resourceUri);
BitmapFrame temp = BitmapFrame.Create(streamInfo.Stream);
var brush2 = new ImageBrush();
brush2.ImageSource = temp;
Uri resourceUri1 = new Uri("/Images/heart.jpg", UriKind.Relative);
StreamResourceInfo streamInfo1 = Application.GetResourceStream(resourceUri1);
BitmapFrame temp1 = BitmapFrame.Create(streamInfo1.Stream);
var brush = new ImageBrush();
brush.ImageSource = temp1;
foreach (Button btn in split1.Children)
{
if (btn.Background == brush2)
btn.Background = brush;
}
foreach (Button btn in split2.Children)
{
if (btn.Background == brush2)
btn.Background = brush;
}
}
The problem is that when I call the function, it does not change the image of the buttons. Please help me, any advice will be great.
That is because you compare references of ImageBrush instances with the == operator. The comparison will always fail, because each ImageBrush that you define in XAML and in your code is a distict instance with a unique reference. Consequently, they are never equal.
I wrote function changeHearts() that suppose to check if the background image is: skull.png , So it will change the image of the button to: heart.jpg .
The most simple solution to this is to not compare the image brushes at all. Your buttons either have a Skull or a Hearts image as background. Now, when you call changeHearts() two things can happen:
A button was Skull and will now be changed to Hearts
A button was Hearts and will now be changed to Hearts
In both cases the result will be that the corresponding buttons will be Hearts, so you could just remove the checks and get the same result.
Comparing brushes is hard as the Equals method won't do the trick either. You would have to create custom comparison logic, e.g. find properties on brushes to compare, but I do not recommend it.
An alternative could be to assign the Tag of your buttons with an identifier for what is currently displayed, Hearts or Skull. This could be a custom enum or a simple string, e.g.:
public enum ButtonType
{
Skull,
Hearts
}
Then assign the the initial button type to your buttons in XAML:
<Button x:Name="XLife1" Tag="{x:Static local:ButtonType.Hearts}" Grid.Column="0" Width="80" Height="80">
<Button.Background>
<ImageBrush ImageSource="/images/heart.jpg"/>
</Button.Background>
</Button>
Adpat your methods to check the Tag property of button and change the tag if it matches:
if (btn.Tag.Equals(ButtonType.Hearts))
{
btn.Tag = ButtonType.Skull;
btn.Background = brush;
}

How to position a borderless form under buttons

I have created 4 buttons dynamically and placed them horizontally using c# win forms.Now i want show a custom tooltip(actually its a borderless form) under each of the 4 buttons on mouse hover event.But how do i position my tooltip form under the buttons??
I have tried the code below but it does not work the desired way.
tooltip.Location = new System.Drawing.Point(b.Left, b.Top);
Where 'tooltip' is tooltip form object & 'b' is the dynamic button.Please advise with some code snippet.
private void B_MouseHover(object sender, EventArgs e)
{
var b = sender as Button;
//MessageBox.Show(Cursor.Position.ToString());
if(b!= null)
{
if (tooltip == null)
{
tooltip = new frmSecQStatToolTipDlg();
}
tooltip.Location = new System.Drawing.Point(b.Left, b.Bottom);
tooltip.data(b.Tag.ToString());
tooltip.Show();
}
}
The way you named it is a bit misleading. As I understand, what you call a tooltip is just a Form. You need to consider 2 things
(1) Form.StartPosition must be set to FormStartPosition.Manual
(2) Form.Location must be in screen coordinates. Note that the Button.Location you are trying to use is in button's parent client coordinates. Control.PointToScreen has to be used for conversion.
In your case, it should be something like this
tooltip.StartPosition = FormStartPosition.Manual;
var topLeft = b.PointToScreen(new Point(0, 0));
tooltip.Location = new Point(topLeft.X, topLeft.Y + b.Height);
When you show the tooltip you can control its location, check show method overloads: https://msdn.microsoft.com/en-us/library/system.windows.forms.tooltip.show.aspx

retrieving data from database with dynamic controls

I have made a voting system for our school. I already made an Add, Update, Delete, and retrieving data from database. I have a problem making a dynamic control automatically with the exact amount of data i have in database. For example, I have added pictures to the two Candidates in the position of President, then, I want it to dynamically create a PictureBox in my new form and retrieve the pictures in a 2 pictureboxes and radiobutton for their names under it. Is it possible for me to do it in array? I'm new to programming so bear with me please.
I'm a little bit confused. Can you make an example of it, if possible please.. :)
This should get you going.
Add this code to your form. And you can use this code for any buttons or anything you want. But you should maybe read up on the FlowLayoutPanel or GroupBox to get this to work in reality.
Point _imagePos = new Point(10,10);
int _imageCounter = 1;
private void NewPictureBox(string pathToImg, string imageName)
{
var img = new PictureBox
{
Name = "imageBox" + _imageCounter,
ImageLocation = pathToImg,
Left = _imagePos.X,
Top = _imagePos.Y,
SizeMode = PictureBoxSizeMode.StretchImage,
Height = 50,
Width = 50
};
var txt = new TextBox
{
Text = imageName,
Left = _imagePos.X,
Top = img.Bottom + 10
};
this.Controls.Add(img);
this.Controls.Add(txt);
_imageCounter++;
_imagePos.Y += 10 + img.Height + txt.Height;
}
private void Form1_Load(object sender, EventArgs e)
{
NewPictureBox(#"C:\test\QuestionMark.jpg", "image1");
NewPictureBox(#"C:\test\QuestionMark.jpg", "image2");
}

creating dynamic textbox in wpf according to location

I'm trying to create dynamically text box in WPF. It is very essential that I will have the flexibility to determine where the text box will be - in pixel level.
I have found many answers which use stackpanel to create "run-time" text box - but couldn't find how to construct it according to specified location.
the textbox has to be "word wrap" and I'm using a button click event to create the text box
this is the code for now, I really don't know which methods or properties will be helpful.
thanks :)
private void button1_Click(object sender, RoutedEventArgs e)
{
TextBox x = new TextBox();
x.Name = "new_textbox";
x.TextWrapping= TextWrapping.Wrap;
x.VerticalScrollBarVisibility=ScrollBarVisibility.Visible;
x.AcceptsReturn = true;
x.Margin = new Thickness(5, 10, 0, 0);
}
TextBox x = new TextBox();
x.Name = "new_textbox";
x.TextWrapping= TextWrapping.Wrap;
x.VerticalScrollBarVisibility=ScrollBarVisibility.Visible;
x.AcceptsReturn = true;
x.Margin = new Thickness(5, 10, 0, 0);
HouseCanvas.Children.Add(x);
Canvas.SetLeft(x, 20);
Canvas.SetTop(x, 20);
You probably want to place it in a Canvas, if you care about pixel placement of the textbox itself. You'll need to use x.SetValue(Canvas.LeftProperty, pixelX) [and .RightProperty, etc...] to get the position exactly right. Having not done this myself, I'd guess that you need to put the canvas in the right Z-order (on top), and make it transparent. There may also be issues with events, depending on the z-order. Good luck!
-Kev

Windows Phone C# - Button color for button array

I've began by creating a large array of buttons, 1 to 96 on my program. The plan was that as one button was pressed it would turn red, which would randomly catch on other buttons near by.
The problem I have is that the button does not wish to turn red whatsoever. Below, I will show the code of my attempt to do so:
public MainPage()
{
InitializeComponent();
numbers = new[] {
button1, button2, button3, button4, button5, button6, button7, button8, button9, button10,
button11, button12, button13, button14, button15, button16, button17, button18, button19,
button20, button21, button22, button23, button24, button25, button26, button27, button28,
button29, button30, button31, button32, button33, button34, button35, button36, button37,
button38, button39, button40, button41, button42, button43, button44, button45, button46,
button47, button48, button49, button50, button51, button52, button53, button54, button55,
button56, button57, button58, button59, button60, button61, button62, button63, button64,
button65, button66, button67, button68, button69, button70, button71, button72, button73,
button74, button75, button76, button77, button78, button79, button80, button81, button82,
button83, button84, button85, button86, button87, button88, button89, button90, button91,
button92, button93, button94, button95, button96
};
}
private void ButtonSequence(int bRef)
{
Random random = new Random();
int activeCell = bRef;
int randomNumber = random.Next(0, 10);
int steps = 0;
int randomMaxRange = 2;
SolidColorBrush red = new SolidColorBrush(Colors.Red);
numbers[activeCell].Background = red;
if (activeCell == 0)
{
randomNumber = random.Next(0, 10);
if (randomNumber < randomMaxRange)
{
steps++;
ButtonSequence(1);
}
This function continues, and is called by:
private void button1_Click(object sender, RoutedEventArgs e)
{
ButtonSequence(0);
}
And others.
Has anyone got a fix for this?
Thanks.
If you need to manually create 96 buttons in your application, you have something wrong with the way you handle your data model. Also, in your code, you are never actually adding the buttons to the page visual tree. Do you have a container for your data somewhere on your page?
You also don't seem to have the event handler tied to the UI control.

Categories

Resources