UserControl在列表绑定中

时间:2014-05-27 16:22:32

标签: .net wpf binding user-controls

简单用户控制

<Grid>
    <StackPanel Orientation="Vertical">
        <TextBlock Text="{Binding Path=Name}"/>
        <TextBlock Text="{Binding Path=DispValue}"/>
    </StackPanel>
</Grid>

public partial class UserControlDocFieldBaseB : UserControl
{
    public DocField DocField { get; set; }
    public UserControlDocFieldBaseB()
    {
        InitializeComponent();
        this.DataContext = DocField = new DocFieldString("ctorDocFieldString", "ctorDocFieldStringValue");
    }
    public UserControlDocFieldBaseB(DocField docField)
    {
        InitializeComponent();
        DocField = docField;
        this.DataContext = DocField;
    }
}

我想将它绑定到列表
它具有正确的项目数,但值均来自默认的ctor()
如何让UserControlDocFieldBaseB使用DocFields?

<ListBox Grid.Row="2" Grid.Column="1" 
         ItemsSource="{Binding Path=DocFields}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <local:UserControlDocFieldBaseB DataContext="{Binding Path=.}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

这适用于单个项目(ucB2是UserControlDocFieldBaseB)

ucB2.DataContext = docFieldSelected;

1 个答案:

答案 0 :(得分:0)

当您这样做时总结评论:

this.DataContext = DocField = new DocFieldString("ctorDocFieldString", "ctorDocFieldStringValue");

您覆盖否则将继承的DataContext值。事实上,您甚至不需要绑定DataContext的{​​{1}},因为它应该通过可视树继承

UserControl