c# - create a ListBox inside an UserControl and bind objects -
i want create listbox inside usercontorl, , than, using usercontrol show , "manage" list in many pages.
for example got list of trucks, each object truck has property name, id...
now create own usercontrol
<usercontrol x:class="crud.view.listboxinusercontrol" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:crud.view" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:ignorable="d" name="myusercontrol" d:designheight="300" d:designwidth="400"> <grid> <listbox x:name="aname" itemssource="{binding ??}"> <stackpanel> <stackpanel orientation="vertical" margin="0,20,0,0"> <textblock text="id"/> <textblock text="{binding id}" /> </stackpanel> <stackpanel orientation="vertical" margin="0,20,0,0"> <textblock text="name"/> <textblock text="{binding name}" /> </stackpanel> </stackpanel> </listbox> </grid>
how can bind items in code behind?
and how can manage "click" on list?
in page.xaml want write
<luc:listboxinusercontrol x:name="mylistbox datacontext="{binding}"/>
and in code behind
private observablecollection<truck> testlist { get; set; } ... testlist = await truckservice.getall(); //a method list mylistbox.myitemssource = testlist;
add listbox usercontrol,
<listbox x:name="aname" selectionchanged="aname_selectionchanged"> <listbox.itemtemplate> <datatemplate> <stackpanel> <stackpanel orientation="vertical" margin="0,20,0,0"> <textblock text="id"/> <textblock text="{binding id}" /> </stackpanel> <stackpanel orientation="vertical" margin="0,20,0,0"> <textblock text="name"/> <textblock text="{binding name}" /> </stackpanel> </stackpanel> </datatemplate> </listbox.itemtemplate> </listbox>
add event handler getting selection changed , public property of listbox bind objects in user control code behind,
public event eventhandler<eventargs> selectionchangedevent; public listboxinusercontrol() { this.initializecomponent(); } private void aname_selectionchanged(object sender, selectionchangedeventargs e) { selectionchangedevent(sender, new eventargs()); } private listbox myvar; public listbox myproperty { { return aname; } set { aname = value; } }
then can add usercontrol in xaml,
<local:listboxinusercontrol x:name="uc_listboxinusercontrol" selectionchangedevent="uc_listboxinusercontrol_selectionchangedevent"> </local:listboxinusercontrol>
in code behind can bind data ,
uc_listboxinusercontrol.myproperty.itemssource = testlist;
and access selection changed event,
private void uc_listboxinusercontrol_selectionchangedevent(object sender, eventargs e) { }
Comments
Post a Comment