as 的妙用
个人理解:as跟is
is 相当于判断里的“==” 是与否
if(e.OriginalSource is Button)
as 一般用来转换另一种object
e.OriginalSource as Button
来获取相关属性或值
e.OriginalSource as RadioButton).Name.ToUpper()
as和is的出现 一般是在路由事件中,需要通过这两个关键字来互交动态生成的不同类型或属性不同的UI控件
比如通过for生成按钮
for(int i = 0;i<10;i++) { Button btn = New Button(); btn.Name = i.ToString();
stackPanel1.Children.Add(btn);
}
for(int i = 0;i<10;i++) { RadioButton btn = New RadioButton();
btn.Name = i.ToString();
stackPanel1.Children.Add(btn);
}
路由监听
this.stackPanel.AddHandler(Button.ClickEvent, new RoutedEventHandler(Btn_Click));
事件处理
private void Btn_Click(object obj, RoutedEventArgs e) { object Obj = e.OriginalSource;
if(Obj is Button)
{
MessageBox.Show((Obj as Button).Name.ToString());
}
if(Obj is RadioButton)
{
MessageBox.Show((Obj as RadioButton).Name.ToString());
}
}
比较复杂的转换,需要一层一层进入
TabControl切换需求
((sender as TabControl).SelectedItem as TabItem).Header.ToString();
DataGrid数据操作需求
((sender as DataGrid).SelectedItem as DataRowView).Row["c_id"].ToString();