Applying correct bindings to WPF datatemplate to maximize reusability
Posted
by johncatfish
on Stack Overflow
See other posts from Stack Overflow
or by johncatfish
Published on 2010-05-31T23:08:47Z
Indexed on
2010/05/31
23:13 UTC
Read the original article
Hit count: 243
Hi. I have a WPF application.
I want to apply that datatemplate to a Listbox filled with records from Table02. Then, for each listboxitem I need to bind the combobox to the same database table (Table01), but for each listboxitem the selected item will vary. It will be a foreign key to Table01.
<DataTemplate x:Key="Table01DataTemplate">
<Grid>
<ComboBox
ItemsSource="{Binding Model.IQueryable_Table01,
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"
SelectedValue="{Binding Table01_ForeignKey}"
DisplayMemberPath="name"
SelectedValuePath="id"
/>
<!-- Other stuff -->
</Grid>
</DataTemplate>
<ListBox x:Name="lbTest" ItemTemplate="{StaticResource Table01DataTemplate}" />
<!-- In .cs file
lbTest.DataContext = this;
-->
Notes: Model.IQueryable_Table01 is a property which encapsulates a Linq-to-sql call returning a IQueryable. lbTest will be filled by setting ItemsSource with a Linq-to-sql call.
Is this a good way to do the bindings in a data template for a maximum reusability? I also thought of replacing
AncestorType={x:Type Window} with lbTest.DataContext = this;
AncestorType={x:Type Application} and lbTest.DataContext = App.Current;
But it didn't work (Exception on loading) and I don't know if there's any caveats or down-sides to this approach.
Is this good? Any suggestions or improvements? Thanks.
© Stack Overflow or respective owner