WPF radiobutton事件处理问题

时间:2011-08-08 15:38:17

标签: wpf events

radio.Checked += new RoutedEventHandler(VariantChecked); 假设我有这个代码。如果我想将参数传递给VariantChecked方法,该怎么办?我应该使用什么语法?

1 个答案:

答案 0 :(得分:1)

在创建过程中,将数据对象附加到DataContext或RadioButton的Tag属性。

RadioButton radio=new RadioButton();
radio.DataContext=yourData;

然后在事件处理程序中,获取数据:

void VariantChecked(object sender, RoutedEventArgs e){ 
   RadioButton  radio=(RadioButton)sender; 
   YourData yourData=(YourData)radio.DataContext; 
}

在上面的例子中,我假设你有一个你想要提供的名为YourData的类或结构。您可以通过任何原语(如string或int或任何其他对象类型)替换它。


以上作品也来自xaml:

<RadioButton Tag="Static Data, could also be a binding" ...

这里我采用了Tag属性,因为它使这种结构更有意义,但也可以采用DataContext。除了从Tag-property进行强制转换外,事件处理程序是相同的。

void VariantChecked(object sender, RoutedEventArgs e){    
   RadioButton  radio=(RadioButton)sender;    
   string yourStringFromTag=(string)radio.Tag; 
}

顺便说一句,你可以通过不指定具体的控件类而是基类来使代码更通用:

void VariantChecked(object sender, RoutedEventArgs e){    
   FrameworkElement fe=(FrameworkElement)sender;    
   string yourStringFromTag=(string)fe.Tag; 
}

希望这有助于......