wpf - Expander inside ListBox not showing content when expanded the first time from binding -
i have dialog window contains listbox
itemtemplate contains expander. isexpanded
bound property in item view model. listboxitem
's isselected
property bound isexpanded
property in item view model object. , selecteditem
property of listbox
bound property same name in view model.
the problem here when setting view model before showing dialog , setting datacontext
of dialog, item in listbox gets selected should, expander arrow shows in expanded state, content of expander not displayed.
if set view model after showing dialog, eg. in loaded handler of dialog things work expected. going on here, , best way fix it?
the dialog window defined as:
<window x:class="wpfapplication1.dialog" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:l="clr-namespace:wpfapplication1" title="dialog" height="300" width="300"> <grid> <listbox itemssource="{binding items}" selecteditem="{binding selecteditem, mode=twoway}"> <listbox.itemtemplate> <datatemplate> <expander header="expander" x:name="myexpander" isexpanded="{binding isexpanded, mode=twoway}"> <rectangle width="100" height="20" fill="red" /> </expander> </datatemplate> </listbox.itemtemplate> <listbox.itemcontainerstyle> <style targettype="listboxitem"> <setter property="isselected" value="{binding isexpanded, mode=twoway}" /> </style> </listbox.itemcontainerstyle> </listbox> </grid>
and viewmodel (implementation not included sake of brevity):
public interface imyviewmodel : inotifypropertychanged { object selecteditem { get; set; } observablecollection<imyitemviewmodel> items { get; } } public interface imyitemviewmodel : inotifypropertychanged { bool isexpanded { get; set; } }
then have simple main window button, , click
handler defined as:
private void button_click(object sender, routedeventargs e) { myviewmodel vm = new myviewmodel(); myitemviewmodel item = new myitemviewmodel(); vm.items.add(item); vm.selecteditem = item; dialog dialog = new dialog(); dialog.datacontext = vm; dialog.showdialog(); }
when run application , click button, dialog shows up, expander arrow indicates in expanded state, content not displayed. clicking on expander collapses it, , clicking again expands it, time showing content. putting same code directly in main window instead of dialog works supposed to.
if dispatcher.begininvoke(new action(() => vm.selecteditem = item);
instead of setting directly things seem work, feels bit shaky.
what can done fix problem?
sounds content of expander not measured again after loaded, if isexpanded
property set true. or put way, content measured when has still no actual size.
i suppose easiest solution set selecteditem
once dialog has been loaded:
dialog.loaded += (s, x) => vm.selecteditem = item;
Comments
Post a Comment