Friday, November 21, 2008

Trips&Ticks: Do you know how you can cast Object to AnonymousType?

I experimented with LINQ in my private project and question that was showed in title took me. I had next situation:

I set list in one method:

private void SetList()
SomeList.ItemsSource = ( from someTable in data.SomeTable
select new
Priority = someTable.Priority,
} );
In other method I want retrieve Id of selected item. How can I do it? I have found interesting solution in blog of Tomas Petricek.
private Int32 GetID()
Object selectedItem = DefectList.SelectedItem;

if( null != selectedItem )
var item = Utility.Cast( selectedItem, new
Id = 0,
Name = String.Empty,
Priority = String.Empty,
} );

Int32 id = item.Id;
public static T Cast( object obj, T type )
return (T)obj;

PS: As for me the best way is:
  • implement class with three like property.
  • create collection with items of this class.
  • set in ItemsSource new created collection.
  • now we can easy case Object to this class.

Tuesday, November 18, 2008

Such different paths. Binding in WPF part 1.

Download source files - here

We pleasure to using Binding in WPF. But all ways of using have we known? Only direct binds to dependency property like next code?

<TextBlock Text="{Binding Path=Height, ElementName=myButton}">

This is poor. We can bind to property of value's property. How?

<TextBlock Text="{Binding Path=Background.(SolidColorBrush.Opacity), ElementName=myButton}"/>


<TextBlock Text="{Binding Path=(Button.Content).(TextBlock.FontSize), ElementName=myButton}"/>

In attached sample I show how we can use this for EventTriggers.