Silverlight: binding an observable collection to different usercontrols conditionally
I'm new to Silverlight 4 and having a tough time googling this one since I'm not terribly familiar with the terminology involved. Can someone point me in the right direction?
I have an observable collection that I want to represent in an ItemsControl list. The type of the collection is a class that- for simplicity's sake- let's call PersonInfo. Each PersonInfo has a string property Name and an observable collection PhoneNumbers. Everything works fine when I tell the ItemsControl's DataTemplate to use "UserControl1" for visualizing the data- the bindings work.
My problem is that- for this theoretical example- I want to base the control used to display the PersonInfo on certain values in the Name propery. So I want to use UserControl1 for any entries named "Joe", and use UserControl2 for all others. I've found IValueConverter stuff, but that doesn't seem to help with selecting the control type used to visualize the data.
Sidenote: UserControl1 and UserControl2 show data in a similar way, but there are some differences within their complicated grid layouts that forced me to create 2 separate usercontrols. If anyone knows how I could build multiple layouts into UserControl1's xaml and then switch between them at runtime via a property binding, that would probably let me sidestep this issue altogether...
Can anyone recommend a general strategy for solving either si开发者_JS百科de of this problem?
Thanks in advance!
I’ve solved a similar dilemma by using an IValueConverter
in an unusual way: I created a "VisibilityConverter" that tells a control whether it ought to appear. In the case of your example you would have two of them: one Convert method would
return ((PersonInfo)o).Name == "Joe" ? Visibility.Visible : Visibility.Collapsed;
and the other would do the opposite. Then bind UserControl1
's visibility to one VisibilityConverter
and bind UserControl2
's visibility to the other and violà, they swap out based on the data.
精彩评论