Answer the question
In order to leave comments, you need to log in
(WPF/C#) Getting Content from one button removes Content from another. What is the problem?
The task is this. There are 2 panels, left and right. In the left column, picture buttons are loaded dynamically (meaning the background of the buttons). When a button is pressed, a copy of the pressed button is created in the right pane.
Problem: the image from the background disappears from the original button.
I create buttons like this:
foreach (FileInfo f in natureAnimalsFileInfo)
{
Button natureAnimalsSmileButton = new Button
{
Width = 60,
Height = 60,
Name = "s_" + f.Name.Replace(".png","") + "",
Content = new Image
{
Source = new BitmapImage(new Uri(Directory.GetCurrentDirectory() + "\\smiles\\NatureAnimals\\" + f.Name)),
VerticalAlignment = VerticalAlignment.Center
}
};
natureAnimalsSmileButton.Click += button1_Click;
NatureAnimals.Items.Add(natureAnimalsSmileButton);
}
private void button1_Click(object sender, RoutedEventArgs e)
{
var Name = (e.Source as Button).Name.ToString();
var Content = (e.Source as Button).Content;
Button button = new Button
{
MinWidth = 60,
Width = 60,
Height = 60,
Name = Name,
Content = Content
};
Test.Items.Add(button);
/*
Button button = new Button();
button.Name = Name;
button.Content = Content;
button.Width = 60;
button.Height = 60;
Test.Items.Add(button);
*/
}
Answer the question
In order to leave comments, you need to log in
The problem is that the Content of the button is an Image (control). A control can only have one parent, and when you assign it to another button, it simply changes the parent from one button to another. Therefore, the image of the first button disappears.
When creating a button, visual elements (Image) need to be created anew. But the loaded image (BitmapImage)) can be used the one that is already loaded.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question