Tuesday 15 February 2011

c# - Binding a code-behind defined property to a DataContext property in XAML? -



c# - Binding a code-behind defined property to a DataContext property in XAML? -

i'm trying bind property defined in page code-behind listview.datacontext property in xaml, reason it's not working in way thought, when run app listview.datacontext not beingness set , remains null, can please help me that?

i looked similar questions of them solve problem setting datacontext manually in code-behind, i'd xaml.

mainpage.xaml class="lang-xml prettyprint-override"><page x:class="customcontrols.mainpage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:customcontrols" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:ignorable="d" background="{themeresource applicationpagebackgroundthemebrush}"> <stackpanel> <listview datacontext="{binding path=mymarket, relativesource={relativesource mode=self}}" itemssource="{binding path=products}" header="{binding path=name}"> <listview.itemtemplate> <datatemplate> <stackpanel> <textblock text="{binding path=id}"/> <textblock text="{binding path=description}"/> </stackpanel> </datatemplate> </listview.itemtemplate> </listview> </stackpanel> </page> mainpage.xaml.cs class="lang-cs prettyprint-override">using system.collections.objectmodel; using windows.ui.xaml.controls; using windows.ui.xaml.navigation; namespace customcontrols { public sealed partial class mainpage : page { public market mymarket { get; private set; } public mainpage() { this.initializecomponent(); this.navigationcachemode = navigationcachemode.required; this.mymarket = new market { name = "my market", products = new observablecollection<product> { new product { id = 123, description = "qwerty" }, new product { id = 234, description = "wertyu" } } }; } } public class product { public int id { get; set; } public string description { get; set; } } public class market { public string name { get; set; } public observablecollection<product> products { get; set; } } }

you have bind page, have @ top of xaml:

<page [..] datacontext="{binding mymarket, relativesource={relativesource self}}">

then should able hook this:

<listview itemssource="{binding path=products}" header="{binding path=name}"> [..]

now switch lines in constructor elements there before page built:

this.mymarket = new market { name = "my market", products = new observablecollection<product> { new product { id = 123, description = "qwerty" }, new product { id = 234, description = "wertyu" } } }; this.initializecomponent(); this.navigationcachemode = navigationcachemode.required;

you should consider using viewmodel classes later on.

c# xaml windows-runtime

No comments:

Post a Comment