Binding without XAML [WPF] - c#

I am designing an application with 256 buttons inside, and I am adding them in the WrapPanel in C# code using for loop. These buttons are not mentioned in XAML code.
My problem is that, when clicking on one of them, I have to change its color using binding.
I tried following code, but it does not work (only changes the content of the button):
private void NewButton_Click(object sender, RoutedEventArgs e)
{
Button btn = (Button)sender;
for (int i = 0; i < counter; i++)
{
if (btn.Name == ("Butt" + i))
{
btn.Content = "works";
MyData mydata = new MyData();
Binding binding = new Binding("Color");
binding.Source = mydata;
binding.Source = btn;
break;
}
}
}
and
private int counter = 0;
public class MyData
{
public static Brush _Color = Brushes.Red;
public Brush Color
{
get
{
return _Color;
}
}
}
public MainWindow()
{
InitializeComponent();
int num = number(3);
List<Button> btnList = new List<Button>();
for(int i =0; i<(num*num); i++)
{
Button button = new Button();
button.Name = "Butt" + counter;
button.Content = "New";
counter++;
button.Height = 35;
button.Width = 35;
button.Click += new RoutedEventHandler(NewButton_Click);
wp.Children.Add(button);
}

If what you are trying to do is bind the button's background color to your "MyData" class object, you are almost there...
First, create the binding object, set the source to your new instance of "mydata", and then the path to your "Color" property exposed.
THEN, you need to save the new BINDING object to your button control and tell it you want the BackgroundProperty bound to the newly created binding. The following minor adjustment to your code works. Not exactly why your approach is what it is for your overall project, but hopefully does what you intended.
if (btn.Name == ("Butt" + i))
{
btn.Content = "works";
MyData mydata = new MyData();
var oBind = new Binding
{
// bind its source to this view model instance
Source = mydata,
// what property on THE BUTTON do want to be bound to.
Path = new PropertyPath("Color")
};
btn.SetBinding(BackgroundProperty, oBind);
btn.DataContext = oBind;
break;
}

Related

How to create databinding in code behind for a textblock that is created also in code behind?

I have the following code :
private void Ok_Click(object sender, MouseButtonEventArgs e)
{
MainWindow win = (MainWindow)Application.Current.MainWindow;
int i = 1; // counter for the name of each new textblock
string name = String.Concat("sample", i);
// add textblok to the document list of new samples
if (File_name.Text != "")
{
TextBlock sampleText = new TextBlock();
sampleText.Text = File_name.Text;
sampleText.FontSize = 14;
sampleText.FontFamily = new FontFamily("Sans-serif");
sampleText.FontWeight = FontWeights.DemiBold;
sampleText.Margin = new Thickness(20,0,0,0);
sampleText.Name = name;
sampleText.PreviewMouseDown += new MouseButtonEventHandler(test1);
sampleText.Visibility = System.Windows.Visibility.Collapsed;
//binding
Binding myBinding = new Binding();
myBinding.Source = Application.Current;
myBinding.Path = new PropertyPath("sampleName");
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
sampleText.SetBinding(, myBinding);
Grid.SetColumn(sampleText, 0);
win.sp_s.Children.Add(sampleText);
// checking if the drop down of sample is already open,
//if so it will show the last textblock with pressing the arrow button.
var TextBlock = win.sp_s.Children.OfType<TextBlock>().FirstOrDefault();
if (TextBlock.Visibility == System.Windows.Visibility.Visible)
{
sampleText.Visibility = System.Windows.Visibility.Visible;
}
}
i += 1; // increasing the loop of names by 1
this.Close();
}
I want to set the target property of the SetBinding method to TextBlock.TextProperty but whenever I write TextBlock I get an error stating
Cannot use local variable 'TextBlock' before it is declared.
I suspect the issue is with this code -
var TextBlock = win.sp_s.Children.OfType<TextBlock>().FirstOrDefault();
if (TextBlock.Visibility == System.Windows.Visibility.Visible)
{
sampleText.Visibility = System.Windows.Visibility.Visible;
}
You have declared a variable name as "TextBlock". The TextBlock.Text property you are trying to set inside the binding is getting confused with this variable name you have declared below it. If you rename this variable the issue might get fixed.
var textblock = win.sp_s.Children.OfType<TextBlock>().FirstOrDefault();
if (textblock.Visibility == System.Windows.Visibility.Visible)
{
sampleText.Visibility = System.Windows.Visibility.Visible;
}

Get Value Dynamic Textbox in C#

I made dynamic textboxes and keep it List
private void ConvertButton_Click(object sender, EventArgs e)
{
List<TextBox> textBoxes = new List<TextBox>();
foreach (Control item in this.Controls)
{
if (item is TextBox)
{
TextBox txt = item as TextBox;
textBoxes.Add(txt);
}
}
}
I get all of textboxes value but i have a problem. For examples; if user add 3 label like (A,B,C) and add Textboxes for them like (labelA has 2,labelB has 3,labelC has 1) and textboxes get value like array (textboxes[0] has value).The problem is i dont know which label has which value.
I added Textbox just like this:
private void addNewTextbox(object sender, EventArgs e)
{
Button button = (Button)sender;
List<TextBox> textBoxes = button.Tag as List<TextBox>;
if (textBoxes == null)
button.Tag = textBoxes = new List<TextBox>();
TextBox textBox = new TextBox();
textBoxes.Add(textBox);
textBox.Location = new Point(90 * textBoxes.Count, button.Top);
textBox.Size = new Size(50, 50);
this.Controls.Add(textBox);
}
I try to show screen for example;
LabelA-->Textbox1 , Textbox2
</br>
labelB -->Textbox3
</br>
LabelC --> Textbox4 , Textbox5 , TextBox6
Every control that is added has a Name property. Use this property to link the different controls together. For example (and you should come up with your own naming convention), you could do this:
LabelA --> TextboxA1, TextboxA2
LabelB --> TextboxB1
LabelC --> TextboxC1, TextboxC2, TextboxC3
If you wish to have a more complete (i.e. complex) solution, you could:
Create your own control that inherits from TextBox
Add a property for the name of the associated Label control
Set this property when a new control is instantiated
Label[] labelArray = new Label[10];
for (int i = 0; i < labelNumber; i++)
{
labelArray[i] = new Label();
labelArray[i].Text = states[i] + "-->";
this.Controls.Add(labelArray[i]);
labelArray[i].Top = 100 + i * 30;
labelArray[i].Left = 10;
labelArray[i].Width = 30;
}
i did label-created just like this.labelnumber is how many label user wants.#interceptwind
I am trying very hard to understand your question, I guess you are trying to link the user-created textboxes to specific labels? Forgive me if I am completely wrong. How about structure your code to something like this:
Note: Edited with OP's new code
Dictionary<Int, List<TextBox>> label_Textboxes_Dict = new Dictionary<Int, List<TextBox>>();
List<Label> labelArray = new List<Label>(); //I suggest use list as you don't know the array size beforehand
void addLabel(int labelNumber)
{
int currentLabelArrayCount = labelArray.count; //So that users can add multiple times
for (int i = currentLabelArrayCount; i < currentLabelArrayCount +labelNumber; i++)
{
labelArray.Add(new Label());
labelArray[i].Text = states[i] + "-->";
this.Controls.Add(labelArray[i]);
labelArray[i].Top = 100 + i * 30;
labelArray[i].Left = 10;
labelArray[i].Width = 30;
label_Textboxes_Dict.Add(i, new List<TextBox>());
}
}
void addTextBoxForLabel(int labelNum)
{
TextBox t1 = new TextBox();
TextBox t2 = new TextBox();
//etc...
if (label_Textboxes_Dict.ContainsKey(labelNum))
{
label_Textboxes_Dict[labelNum].Add(t1);
label_Textboxes_Dict[labelNum].Add(t2);
}
}
void doSomethingForAllTextboxesOfLabel(int labelNum)
{
List<TextBox> listOfTextBoxes;
if(label_Textboxes_Dict.TryGetValue(labelNum, out listOfTextBoxes))
{
foreach(TextBox tb in listOfTextBoxes)
{
//do your stuff
}
}
}

Removing or Hide dynamically created linklabels and labels

Background
I create a set of linklabel and label controls using a loop that uses data from a database as there content (Text).
Question
How do I then remove or change there visibility?
What I would Like to Happen?
On a button click event, I would like all of the link's and linklabel's text properties to be set to either null, or their visibility properties to be set as false.
Code
private void getInfoStationID()
{
//SQL Connection Stuff
for (int i = 0; i <= rowCount - 1; i++)
{
LinkLabel Linklabel = new LinkLabel();
Linklabel.Text = ds.Tables[0].Rows[i] ["code"].ToString();
Linklabel.Height = 15;
Linklabel.Width = 50;
Linklabel.AutoSize = true;
Linklabel.Location = new Point(10, (i + 1) * 30);
tabControl1.TabPages[0].Controls.Add(Linklabel);
// Add an event handler to do something when the links are clicked.
Linklabel.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked);
Label label1 = new Label();
label1.Text = ds.Tables[0].Rows[i]["name"].ToString();
label1.Height = 15;
label1.Width = 70;
label1.Location = new Point(100, (i + 1) * 30);
tabControl1.TabPages[0].Controls.Add(label1);
Label label3 = new Label();
label3.Text = ds.Tables[0].Rows[i]["toc"].ToString();
label3.Height = 15;
label3.Width = 50;
label3.Location = new Point(240, (i + 1) * 30);
tabControl1.TabPages[0].Controls.Add(label3);
}
}
private void clearAllBtn_Click(object sender, EventArgs e)
{
//Would like this to clear all previously drawn labels and linklabels
}
Simply add the dynamic controls to a List so you have a quick reference to them:
// out at CLASS/FORM level:
private List<Control> MyControls = new List<Control>();
// ... some method ...
for (int i = 0; i <= rowCount - 1; i++)
{
LinkLabel Linklabel = new LinkLabel();
MyControls.Add(Linklabel);
// ... rest of your code ...
Label label1 = new Label();
MyControls.Add(label1);
// ... rest of your code ...
Label label3 = new Label();
MyControls.Add(label3);
// ... rest of your code ...
}
Now you can use that List from somewhere else:
private void clearAllBtn_Click(object sender, EventArgs e)
{
foreach(Control ctl in MyControls)
{
ctl.Visible = false; // or something else
}
}
*Don't forget to dispose of those controls and empty the list if you decide to create a new set of dynamic controls. If you want to completely get rid of them:
private void clearAllBtn_Click(object sender, EventArgs e)
{
foreach(Control ctl in MyControls)
{
ctl.Dispose();
}
MyControls.Clear();
}
You can loop through all controls on a certain tabpage. You could use a open generic function to make the code nice and clean. Like this:
private void HideControls<TControl>(Control parentControl)
where TControl : Control
{
var controls = parentControl.Controls.OfType<TControl>();
foreach (var control in controls)
{
control.Visible = false;
}
}
And use it like this:
private void button1_Click(object sender, EventArgs e)
{
this.HideControls<Label>(tabControl1.TabPages[0]);
this.HideControls<LinkLabel>(tabControl1.TabPages[0]);
}
You could even refactor this to a nice extension method:
public static class ControlExtensions
{
public static void HideControlsOfType<TControl>(this Control parentControl)
where TControl : Control
{
var controls = parentControl.Controls.OfType<TControl>();
foreach (var control in controls)
{
control.Visible = false;
}
}
}
and use like:
this.tabControl1.TabPages[0].HideControlsOfType<Label>();

Add label under button in a flowLayoutPanel

I need to dynamically create buttons with labels under them in a flowLayoutPanel when i drop a file onto the form. But how do I set the label position to be under the button since the FLP is arranging the controls by itself.. ?
What I've tried:
void Form1_DragDrop(object sender, DragEventArgs e)
{
string[] fileList = e.Data.GetData(DataFormats.FileDrop) as string[];
foreach (string s in fileList)
{
Button button = new Button();
button.Click += new EventHandler(this.button_Click);
fl_panel.Controls.Add(button);
Icon icon = System.Drawing.Icon.ExtractAssociatedIcon(filename);
Bitmap bmp = icon.ToBitmap();
button.BackgroundImage = bmp;
button.Width = 60;
button.Height = 75;
button.FlatStyle = FlatStyle.Flat;
button.BackgroundImageLayout = ImageLayout.Stretch;
int space = 5;
int Yy = button.Location.Y;
int Xx = button.Location.X;
Label label = new Label();
label.Location = new Point(Yy + space, Xx);
//label.Margin.Top = button.Margin.Bottom;
fl_panel.Controls.Add(label);
}
}
The best idea I know of is to implement a custom control that contains both a button and a label that are arranged correctly. Then add the custom control to the FlowLayoutPanel.
public class CustomControl:Control
{
private Button _button;
private Label _label;
public CustomControl(Button button, Label label)
{
_button = button;
_label = label;
Height = button.Height + label.Height;
Width = Math.Max(button.Width, label.Width);
Controls.Add(_button);
_button.Location = new Point(0,0);
Controls.Add(_label);
_label.Location = new Point(0, button.Height);
}
}
You can then add to it like this:
for (int i = 0; i < 10; i++)
{
CustomControl c = new CustomControl(new Button {Text = "Button!"}, new Label {Text = "Label!"});
fl_panel.Controls.Add(c);
}
EDIT:
If you want to listen to button events, try this:
for (int i = 0; i < 10; i++)
{
var button = new Button {Text = "Button " + i};
CustomControl c = new CustomControl(button, new Label {Text = "Label!"});
button.Click += buttonClicked;
fl_panel.Controls.Add(c);
}
...
private void buttonClicked(object sender, EventArgs e)
{
MessageBox.Show(((Button) sender).Text);
}

Visual Studio-style undo drop-down button - custom ToolStripSplitButton

I'm looking to implement a Visual Studio-style undo drop-down button:
I've looked all over the internet, and can't seem to find any real implementations of this.
I've started by deriving from ToolStripSplitButton, but don't really know where to go from there. Its DropDown property is a ToolStripDropDown, but that doesn't seem to have anything regarding multiple items being selected, much less scrolling, and the text at the bottom.
So instead of the default ToolStripDropDown, I'm thinking maybe the whole drop down part should be a custom control, based on a combobox. The question then, is how to cause the right-side (drop down arrow) button to do something other than show its default drop down?
Am I on the right track here? Thanks!
Yes, I think you're on the right track. And in this case, ToolStripControlHost is your friend.
You don't necessarily need to derive from it (unless you are making your own control), but try just subscribing to the ToolStripSplitButton's DropDownOpening event:
Working example:
private ListBox listBox1;
public Form1()
{
InitializeComponent();
listBox1 = new ListBox();
listBox1.IntegralHeight = false;
listBox1.MinimumSize = new Size(120, 120); \\ <- important
listBox1.Items.Add("Item 1");
listBox1.Items.Add("Item 2");
}
private void toolStripSplitButton1_DropDownOpening(object sender, EventArgs e) {
ToolStripControlHost toolHost = new ToolStripControlHost(listBox1);
toolHost.Size = new Size(120, 120);
toolHost.Margin = new Padding(0);
ToolStripDropDown toolDrop = new ToolStripDropDown();
toolDrop.Padding = new Padding(0);
toolDrop.Items.Add(toolHost);
toolDrop.Show(this, new Point(toolStripSplitButton1.Bounds.Left,
toolStripSplitButton1.Bounds.Bottom));
}
Here is the result:
For your application, you would need to replace the ListBox with your own UserControl, so you can contain whatever your want in it. The ToolStripControlHost can only hold one control, and it's important to set the MinimumSize property, or else the dropped control isn't sized correctly.
Extra thanks to LarsTech! (I didn't know about ToolStripControlHost a few hours ago)
Here is my implementation, which is really close to the VS drop down...
You should be able to just drop this delegate & function into your Form:
public delegate void UndoRedoCallback(int count);
private void DrawDropDown(ToolStripSplitButton button, string action, IEnumerable<string> commands, UndoRedoCallback callback)
{
int width = 277;
int listHeight = 181;
int textHeight = 29;
Panel panel = new Panel()
{
Size = new Size(width, textHeight + listHeight),
Padding = new Padding(0),
Margin = new Padding(0),
BorderStyle = BorderStyle.FixedSingle,
};
Label label = new Label()
{
Size = new Size(width, textHeight),
Location = new Point(1, listHeight - 2),
TextAlign = ContentAlignment.MiddleCenter,
Text = String.Format("{0} 1 Action", action),
Padding = new Padding(0),
Margin = new Padding(0),
};
ListBox list = new ListBox()
{
Size = new Size(width, listHeight),
Location = new Point(1,1),
SelectionMode = SelectionMode.MultiSimple,
ScrollAlwaysVisible = true,
Padding = new Padding(0),
Margin = new Padding(0),
BorderStyle = BorderStyle.None,
Font = new Font(panel.Font.FontFamily, 9),
};
foreach (var item in commands) { list.Items.Add(item); }
if (list.Items.Count == 0) return;
list.SelectedIndex = 0;
ToolStripControlHost toolHost = new ToolStripControlHost(panel)
{
Size = panel.Size,
Margin = new Padding(0),
};
ToolStripDropDown toolDrop = new ToolStripDropDown()
{
Padding = new Padding(0),
};
toolDrop.Items.Add(toolHost);
panel.Controls.Add(list);
panel.Controls.Add(label);
toolDrop.Show(this, new Point(button.Bounds.Left + button.Owner.Left, button.Bounds.Bottom + button.Owner.Top));
// *Note: These will be "up values" that will exist beyond the scope of this function
int index = 1;
int lastIndex = 1;
list.Click += (sender, e) => { toolDrop.Close(); callback(index); };
list.MouseMove += (sender, e) =>
{
index = Math.Max(1, list.IndexFromPoint(e.Location) + 1);
if (lastIndex != index)
{
int topIndex = Math.Max(0, Math.Min(list.TopIndex + e.Delta, list.Items.Count - 1));
list.BeginUpdate();
list.ClearSelected();
for (int i = 0; i < index; ++i) { list.SelectedIndex = i; }
label.Text = String.Format("{0} {1} Action{2}", action, index, index == 1 ? "" : "s");
lastIndex = index;
list.EndUpdate();
list.TopIndex = topIndex;
}
};
list.Focus();
}
You can set it up and test like this, assuming you have a blank form (Form1) with a toolStrip that has 1 ToolStripSplitButton (toolStripSplitButton1) added:
public Form1()
{
InitializeComponent();
// Call DrawDropDown with:
// The clicked ToolStripSplitButton
// "Undo" as the action
// TestDropDown for the enumerable string source for the list box
// UndoCommands for the click callback
toolStripSplitButton1.DropDownOpening += (sender, e) => { DrawDropDown(
toolStripSplitButton1,
"Undo",
TestDropDown,
UndoCommands
); };
}
private IEnumerable<string> TestDropDown
{
// Provides a list of strings for testing the drop down
get { for (int i = 1; i < 1000; ++i) { yield return "test " + i; } }
}
private void UndoCommands(int count)
{
// Do something with the count when an action is clicked
Console.WriteLine("Undo: {0}", count);
}
Here is a better example using the Undo/Redo system from: http://www.codeproject.com/KB/cs/AutomatingUndoRedo.aspx
public Form1()
{
InitializeComponent();
// Call DrawDropDown with:
// The Undo ToolStripSplitButton button on the Standard tool strip
// "Undo" as the action name
// The list of UndoCommands from the UndoRedoManager
// The Undo method of the UndoRedoManager
m_TSSB_Standard_Undo.DropDownOpening += (sender, e) => { DrawDropDown(
m_TSSB_Standard_Undo,
"Undo",
UndoRedoManager.UndoCommands,
UndoRedoManager.Undo
); };
}
*Note: I did modify the Undo & Redo methods in the UndoRedoManager to accept a count:
// Based on code by Siarhei Arkhipenka (Sergey Arhipenko) (http://www.codeproject.com/KB/cs/AutomatingUndoRedo.aspx)
public static void Undo(int count)
{
AssertNoCommand();
if (CanUndo == false) return;
for (int i = 0; (i < count) && CanUndo; ++i)
{
Command command = history[currentPosition--];
foreach (IUndoRedo member in command.Keys)
{
member.OnUndo(command[member]);
}
}
OnCommandDone(CommandDoneType.Undo);
}
I'd suggest implementing the popup separately from the toolbar button. Popups are separate windows with a topmost-flag which auto-close when losing focus or pressing escape. If you code your own popup window that frees you from having to fit your behaviour to a preexisting model (which is going to be hard in your case). Just make a new topmost window with a listbox and status bar, then you are free to implement the selection behavior on the listbox like you need it.
Vs 2010 is a WPF application. If you are in the beginning of this application development than use WPF as a core technology. WPF drop down button is implemented in WPF ribbon. Source code is available on CodePlex.

Categories