binding a usercontrol inside of a ListBox dataTemplate control silverlight
I have a user control as follows:
<UserControl x:Class="CaseDatabase.Controls.SearchResultControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="192" d:DesignWidth="433">
<Grid x:Name="LayoutRoot" Background="White" Height="230" Width="419">
<Grid.RowDefinitions>
<RowDefinition Height="68*" />
<RowDefinition Height="90*" />
</Grid.RowDefinitions>
<TextBlock x:Name="TitleLink" Height="33" Text="{Binding CaseTitle}" HorizontalAlignment="Left" Margin="12,12,0,0" VerticalAlignment="Top" Width="100" Foreground="Red"/>
</Grid>
with a dependency property for CaseTitle:
public string CaseTitle
{
get { return (string)GetValue(TitleProperty); }
set {
SetValue(TitleProperty, value); }
}
// Using a DependencyProperty as the backing store for Title. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TitleProperty =
DependencyProperty.Register("CaseTitle", typeof(string), typeof(SearchResultControl), new PropertyMetadata(new PropertyChangedCallback(SearchResultControl.OnValueChanged)));
in my .xaml page I have a listbox and inside its datatemplate I instanciate my control. This listbox's ItemsSource is binding to a domain Service. I know the binding works and I get the appropiate number of elemets but no data is displayed whatsoever.
the code for my listbox is the following:
<ListBox x:Name="SearchResultsList" Width="Auto" MinHeight="640" ItemsSource="{Binding ElementName=SearchDomainDataSource, Path=Data}"
Grid.Row="0" Grid.Column="0">
<ListBox.ItemTemplate>
开发者_开发问答 <DataTemplate>
<Grid x:Name="LayoutRoot" Background="White" Height="158" Width="400">
<my:SearchResultControl CaseTitle="{Binding Path=Title}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
So can anybody suggest how am I messing up my binding to my user control? Thankx
The problem is that the {Binding CaseTitle}
isn't finding the CaseTitle
dependency property you created. The default Source
object that a Binding uses is the current value of DataContext
property of the element to which it is bound. That object is not the UserControl
.
You therefore need to change that binding as follows:-
<TextBlock x:Name="TitleLink" Height="33" Text="{Binding Parent.CaseTitle, ElementName=LayoutRoot}" HorizontalAlignment="Left" Margin="12,12,0,0" VerticalAlignment="Top" Width="100" Foreground="Red"/>
Now the source object of the binding becomes the Grid
with the name "LayoutRoot" which is the direct child of the UserControl
, hence its Parent
property is the user control and from there you can bind to the CaseTitle
property.
精彩评论