pfinferno pfinferno - 3 months ago 10
C# Question

Using one function to clear one of multiple ListBoxes

I have three

ListBoxes
and three 'clear'
buttons
, one for each of those three
Listboxes
. Right now, I have all of the 'clear'
buttons
linked to the same click-function. In that function, I use a
switch
to determine which
ListBox
to clear. I was wondering if there is a way to get rid of the
switch
statement and replace it with one line of code that determines which
ListBox
to clear. I need something that links each
button
with the corresponding
ListBox
. I messed around with the
Tag
property of the
Buttons
but didn't have luck there.

Here's the code currently:

Xaml (ClearBtn1 clears lb1, etc.):

<Button Name="ClearBtn1"
Click="ClearBtn_Click"
Content="Clear" />

<Button Name="ClearBtn2"
Click="ClearBtn_Click"
Content="Clear" />

<Button Name="ClearBtn3"
Click="ClearBtn_Click"
Content="Clear" />

<ListBox Name="lb1" />

<ListBox Name="lb2" />

<ListBox Name="lb3" />


Code behind:

private void ClearBtn_Click(object sender, RoutedEventArgs e)
{
Button btn = (Button)sender;
string name = btn.Name; //Gets the button name which corresponds to a certain listbox

switch (name)
{
case "ClearBtn1":
{ ClearListBox(lb1); return; }
case "ClearBtn2":
{ ClearListBox(lb2); return;}
case "ClearBtn3":
{ ClearListBox(lb3); return; }
}
}

public void ClearListBox(ListBox listbox)
{
listbox.Items.Clear();
}


With the
Tag
I was trying something like:

<Button Name="ClearBtn1"
Click="ClearBtn_Click"
Content="Clear"
Tag="lb1" />

private void ClearBtn_Click(object sender, Rout
{
Button btn = (Button)sender;
string name = btn.Name;

ClearListBox(btn.Tag); //doesn't work
}


This doesn't work since I can't cast a
string
to a
ListBox
.

Joe Joe
Answer

Try binding the element to the tag, rather than just the string:

<Button Name="ClearBtn1"
    Click="ClearBtn_Click"
    Content="Clear"
    Tag="{Binding ElementName=lb1}"/>
Comments