问题
I have a problem with the Gtk.RadioButton
widget's Clicked
event.
Here is the example code:
using System;
using Gtk;
public partial class MainWindow: Gtk.Window
{
public MainWindow (): base (Gtk.WindowType.Toplevel)
{
Build ();
RadioButton rbt1 = new RadioButton (null, "rbt1");
RadioButton rbt2 = new RadioButton (rbt1, "rbt2");
RadioButton rbt3 = new RadioButton (rbt1, "rbt3");
VBox vbx1 = new VBox ();
vbx1.PackStart (rbt1, false, false, 0);
vbx1.PackStart (rbt2, false, false, 0);
vbx1.PackStart (rbt3, false, false, 0);
this.Add (vbx1);
this.ShowAll ();
rbt1.Clicked+= HandleClicked;
rbt2.Clicked+= HandleClicked1;
rbt3.Clicked+= HandleClicked2;
}
void HandleClicked2 (object sender, EventArgs e)
{
Console.WriteLine ("rbt3.Clicked");
}
void HandleClicked1 (object sender, EventArgs e)
{
Console.WriteLine ("rbt2.Clicked");
}
void HandleClicked (object sender, EventArgs e)
{
Console.WriteLine ("rbt1.Clicked");
}
}
The issue is:
When i click rbt2, the output is :
rbt1.Clicked
rbt2.Clicked
When i click rbt3, the output is :
rbt2.Clicked
rbt3.Clicked
When i click rbt1, the output is:
rbt3.Clicked
rbt1.Clicked
But what I expect is that when I click rbt*, the only output is "rbt*.Clicked".
回答1:
Your expectation is wrong. You should connect to the Toggled
signal instead and check whether the button is being activated or deactivated:
void HandleToggled(object sender, EventArgs e)
{
if(sender.Active)
{
Console.WriteLine("rbt1.Toggled");
}
}
In your case, the Clicked
signal is called when the button is activated or deactivated. Clicking on a deactivated button activates it, and deactivates a different button, so two signals are called. The Toggled
signal is also called in both cases. I'm not quite sure what the difference is, it may be that Clicked
is not guaranteed to be called if the button's state is changed programmatically.
来源:https://stackoverflow.com/questions/10755541/mono-gtk-radiobutton-clicked-event-firing-twice