wpf listbox and datatemplate with grid inside -
i have following question. want have listbox
datatemplate
grid
. grid has 2 two columns. want set first column width 3*
, *
. how this? copy code.
<listbox x:name="commandlistbox" grid.row="1" grid.column="0" grid.columnspan="2" horizontalalignment="stretch"> <listbox.itemtemplate> <datatemplate> <grid> <grid.columndefinitions> <columndefinition width="3*" /> <columndefinition width="*" /> </grid.columndefinitions> <textblock grid.column="0" text="{binding}"/> <textblock grid.column="1" text="icon" /> </grid> </datatemplate> </listbox.itemtemplate> </listbox>
better store template in resources:
<window.resources> <datatemplate x:key="defaulttemplate"> <grid x:name="griditem" width="200"> <grid.columndefinitions> <columndefinition width="auto" /> <columndefinition width="auto" /> </grid.columndefinitions> <textblock x:name="parameter" grid.column="1" text="{binding path=name}" margin="5,1,0,0" /> <textblock x:name="value" grid.column="2" text="{binding path=age}" margin="85,1,0,0" /> <line x:name="separator" x1="0" x2="0" y1="0" y2="20" snapstodevicepixels="true" grid.column="1" stroke="black" strokethickness="2" margin="50,0,0,0" horizontalalignment="left" /> </grid> </datatemplate> </window.resources>
listbox define:
<listbox name="mylistbox" itemtemplate="{staticresource defaulttemplate}" />
in code c#:
public class person { public string name { get; set; } public int age { get; set; } }
define observablecollection:
private observablecollection<person> mylistboxdata = new observablecollection<person>();
and add items on collection:
mylistboxdata.add(new person() { name = "nick", age = 21, }); mylistboxdata.add(new person() { name = "adam", age = 11, }); mylistbox.itemssource = mylistboxdata;
edited:
then set width="3*", width="*" , margin="-widthgrid" of first textblock:
<grid x:name="griditem" width="300"> <grid.columndefinitions> <columndefinition width="3*" /> <columndefinition width="*" /> </grid.columndefinitions> <textblock x:name="parameter" grid.column="1" text="{binding path=name}" margin="-220,0,0,0" /> <textblock x:name="value" grid.column="2" text="{binding path=age}" margin="0,0,0,0" /> </grid>