【问题标题】:binding a usercontrol inside of a ListBox dataTemplate control silverlight在 ListBox dataTemplate 控件中绑定用户控件 silverlight
【发布时间】:2011-05-21 21:44:56
【问题描述】:

我有一个用户控件如下:

<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 的依赖属性:

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

在我的 .xaml 页面中,我有一个列表框,在它的数据模板中,我实例化了我的控件。此列表框的 ItemsSource 绑定到域服务。我知道绑定有效,并且我得到了适当数量的元素,但没有显示任何数据。

我的列表框的代码如下:

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

那么任何人都可以建议我如何弄乱我与用户控件的绑定吗?谢谢x

【问题讨论】:

    标签: silverlight data-binding listbox


    【解决方案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"/> 
    

    现在绑定的源对象变成了名为“LayoutRoot”的Grid,它是UserControl 的直接子对象,因此它的Parent 属性是用户控件,您可以从那里绑定到CaseTitle 属性。

    【讨论】:

      猜你喜欢
      • 2011-11-22
      • 1970-01-01
      • 1970-01-01
      • 2010-12-20
      • 2011-11-15
      • 2011-05-05
      • 2016-07-05
      • 2011-12-17
      • 1970-01-01
      相关资源
      最近更新 更多