Wpf UserControl作为ItemsControl中的数据模板

Wpf UserControl作为ItemsControl中的数据模板,wpf,user-controls,itemscontrol,Wpf,User Controls,Itemscontrol,我试图在ItemsControl中使用UserControl作为DataTemplate。UserControl称为WorkItemControl,绑定到ItemsControl的ItemsSource的observeCollection中的对象类型为WorkItemModel 我在启用绑定诊断时遇到以下错误 BindingExpression路径错误: 'ItemModelText' property not found on 'object' ''WorkItemControl' (Name

我试图在
ItemsControl
中使用
UserControl
作为
DataTemplate
UserControl
称为
WorkItemControl
,绑定到
ItemsControl
ItemsSource
observeCollection
中的对象类型为
WorkItemModel

我在启用绑定诊断时遇到以下错误

BindingExpression
路径错误:

'ItemModelText' property not found on 'object' ''WorkItemControl' (Name='')'. 
BindingExpression:Path=ItemModelText; DataItem='WorkItemControl' (Name='');
target element is 'WorkItemControl' (Name=''); target property is 'ItemText' (type 'String')
如果将按钮用作DataTemplate,而不是UserControl,则可以正常工作`

下面的XAML代码片段显示了
ItemsControl

    <Border Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3" BorderThickness="0" BorderBrush="Black">
        <ItemsControl Name="WorkItems" ItemsSource="{Binding Path=WorkItemModels}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel HorizontalAlignment="Left" Orientation="Horizontal" />
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <control:WorkItemControl ItemText="{Binding Path=ItemModelText}"/>
                    <!--<Button Content="{Binding Path=ItemModelText}"/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </Border>


我不确定我能写下我认为。。。 您需要RelativeSource=Self来在UserControl的XAML中使用UserControl的属性,但是当您尝试将属性绑定到外部时,同样的RelativeSource会妨碍您。我面临着同样的问题。我设法通过设置外部绑定的来源来解决这个问题,但我认为这不是一个非常优雅的方式。事实上,我认为这是WPF中的一个设计问题,因为(在我看来)UserControl中的RelativeSource不应该影响它之外的任何绑定(但它确实影响)。
如果你能用更好的方法解决这个问题,请告诉我。谢谢。

您可能正在将WorkItemControl的DataContext设置为自身。然后DataTemplate中的绑定将尝试在控件而不是数据项上查找
ItemModelText
属性。因此,当您想在DataTemplate中使用WorkItemControl时,不要设置其DataContext……我找到了一个解决方案,从UserControl中删除RelativeSource,并将其添加到其子网格中,但不要使用“Self”参数,而是这样: