Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // assume we have a drop-down list (ComboBox) and we want to access the Tag property of the selected item, which is of type Thing:
- someComboBox.Items.Append( new ComboBoxItem { Content = thing.Name, Tag = thing } );
- // accessing the above is often ugly and hard to read:
- void OnSelectionChanged( System.Object sender, SelectionChangedEventArgs e ) {
- var thing = (Thing)((ComboBoxItem)((ComboBox)sender).SelectedItem)?.Tag;
- }
- // notice our eyes had to ping-pong back and forth to make sense of the casting
- // but add just one helper extension method:
- public static class Extensions {
- public static T As<T>( this System.Object obj ) where T : class => ( obj as T );
- }
- void OnSelectionChanged( System.Object sender, SelectionChangedEventArgs e ) {
- var thing = sender.As<ComboBox>().SelectedItem.As<ComboBoxItem>()?.Tag.As<Thing>();
- }
- // simple, straight-forward, elegant, easy to read because it is now LEFT-TO-RIGHT
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement