【问题标题】:Binding error when using two same User Controls on one parent Window在一个父窗口上使用两个相同的用户控件时出现绑定错误
【发布时间】:2012-11-26 14:08:15
【问题描述】:

我有一个这样定义的用户控件:

XAML:

<UserControl>
<Grid x:Name="LayoutRoot">
    <TabControl x:Name="TabControl" ItemsSource="{Binding Products}" >
        <TabControl.ContentTemplate>
            <DataTemplate>
                <Grid>
                    <ListView ItemsSource="{Binding Features}" Name="FeaturesListView">
                        <ListView.View>
                            <GridView>
                                <GridViewColumn x:Name="FeatureHeader" DisplayMemberBinding="{Binding Name}"  />
                                <GridViewColumn x:Name="CounterHeader" DisplayMemberBinding="{Binding Counter}" />
                                <GridViewColumn x:Name="ExpireDateHeader"  DisplayMemberBinding="{Binding ExpireDate}" />
                            </GridView>
                        </ListView.View>
                    </ListView>
                </Grid>
            </DataTemplate>
        </TabControl.ContentTemplate>
    </TabControl>
</Grid>

后面的代码:

public partial class LicenseInfoControl : UserControl
{
    public LicenseInfoControl(ShowableLicense license)
    {
        InitializeComponent();
        DataContext = license;
    }
}

所以,如果我对一个窗口使用一个用户控件:

<Window>
    <Grid>
        <local:LicenseInfoControl x:Name="LicenseInfoControl"/>
    </Grid>
</Window>

效果很好。但如果我使用其中两个:

<Window>
    <Grid>
        <local:LicenseInfoControl x:Name="FileLicenseInfoControl"/>
        <local:LicenseInfoControl x:Name="SamLicenseInfoControl"/>
    </Grid>
</Window>

两个 ListView 都是空的。我做错了什么?

【问题讨论】:

  • 您在问题标题中提到的绑定错误是什么?
  • @Rachel 如果我使用 2 个用户控件,则两个 ListView 都是空的。其他绑定在这两种情况下都能正常工作。
  • 如果从代码隐藏中设置每个 LicenseInfoControl 的 DataContext 会发生什么?
  • 我已经这样做了(我只是没有足够的空间;))InitializeComponent(); FileLicenseInfoControl.Initilize(fileLic); SamLicenseInfoControl.Initilize(samLic);

标签: wpf data-binding user-controls


【解决方案1】:

绑定效果很好。问题是,如果 TabControl 有一个 TabItem - 它在加载窗口并且数据暴露在其中时被选中。但是如果 TabControl 有两个 TabItems - 没有一个被选中,并且感觉绑定不起作用。但是,如果您选择选项卡项之一 - 数据会立即公开。 所以决定是在带有两个用户控件的窗口构造函数中设置 SelectedIndexes (在我的例子中是 LicenseInfoControl):

FileLicenseInfoControl.ProductTabControl.SelectedIndex = 0;
SamLicenseInfoControl.ProductTabControl.SelectedIndex = 0;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-10
    相关资源
    最近更新 更多