2010-12-07 81 views
1

我有一個用戶控件,如下所示的內部:綁定用戶控件的一個ListBox的DataTemplate控制的Silverlight

<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> 

與依賴屬性CaseTitle:在我的.xaml

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))); 

頁面我有一個列表框,並在其datatemplate內部我instanciate我的控制。此列表框的ItemsSource綁定到域Service。我知道綁定的作品,我得到了適當數量的元素,但沒有顯示任何數據。

我的列表框的代碼如下:

<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> 

所以任何人可以建議我怎麼搞亂了我的綁定到我的用戶控制? Thankx

回答

1

問題是{Binding CaseTitle}未找到您創建的CaseTitle依賴項屬性。 Binding使用的默認對象Source是它綁定到的元素的當前值DataContext屬性。該對象不是UserControl

你因此需要更改綁定,如下所示: -

<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"/> 

現在綁定的源對象變爲Grid名爲「LayoutRoot」,這是UserControl的直接孩子,因此它的Parent屬性是用戶控件,從那裏你可以綁定到CaseTitle屬性。

+0

非常感謝。這工作完美 – Andres 2010-12-09 14:23:16