wpf - How to switch between 2 data sources for ListBox.ItemsSource -
what best/elegant way bind itemscontrol.itemssource 2 different sources best on given property?
the binding should done 1 of 2 collection, selection collection itemscontrol bound should based on property.
i have view bound viewmodel. collections want bind located in different hierarchy path under viewmodel.
i've solution based on multibinding think there should more elegant solution.
<collectionviewsource x:key="cvs"> <collectionviewsource.source > <multibinding converter="{staticresource mymultibindingconverter}"> <binding path="xxxx.yyyy.observablecollection1" /> <binding path="xxxx.observablecollection2" /> </multibinding> </collectionviewsource.source> </collectionviewsource> <listbox x:name="mylistbox" itemssource="{binding source={staticresource cvs}}" />
the converter:
public class mymultibindingconverter : imultivalueconverter { public object convert(object[] values, type targettype, object parameter, system.globalization.cultureinfo culture) { foreach (var item in values) { if(mydependecyproperty == getfirstcollection) { //make sure item of first collection type based on item property return item; } else { //make sure item of second collection type return item; } } return null; } public object[] convertback(object value, type[] targettypes, object parameter, system.globalization.cultureinfo culture) { throw new notimplementedexception(); } }
a datatrigger
more appropriate here since want change itemssource
binding based on value
<style x:key="mylistboxstyle" targettype="listbox"> <setter property="itemssource" value="{binding xxx.observablecollection2}" /> <style.triggers> <datatrigger binding="{binding somevalue}" value="secondcollection"> <setter property="itemssource" value="{binding xxx.yyy.observablecollection2}" /> </datatrigger> </style.triggers> </style>
unlike converter, datatrigger
correctly re-evaluated whenever triggered value changes
Comments
Post a Comment