微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法将TabControl绑定到ObservableCollection

如何解决无法将TabControl绑定到ObservableCollection

搜索了其他类似的问题,但仍然无法将我的收藏绑定到TabControl。 我设法以编程方式添加标题内容。但是,我想使用DataBinding

我定义了带有属性的Struct。我将其插入一个公共的ObservableCollection中,并尝试将其绑定到TabControl。

这是结构的C#代码

   public struct ProbDiffList
{
    /// <summary>
    /// Initializes a new instance of the <see cref="ProbDiffList"/> struct.
    /// Construit une structure avec un identifiant de niveau et une liste de Problème à résoudre.
    /// </summary>
    /// <param name="diff">Niveau de difficulté.</param>
    /// <param name="lstProbleme">List de nom de Problème.</param>
    public ProbDiffList(string diff,List<string> lstProbleme)
    {
        NiveauProb = diff;
        LstProbName = lstProbleme;
    }

    /// <summary>
    /// Gets l'identification du niveau.
    /// </summary>
    public string NiveauProb { get; private set; }

    /// <summary>
    /// Gets la liste des problèmes.
    /// </summary>
    public List<string> LstProbName { get; private set; }
}

这是XAML

           <TabControl x:Name="GamesList"
                    Margin="10"
                    Padding="10"
            DataContext="probClasser">

            <TabItem Header="{Binding probClasser/NiveauProb}"
                         FontWeight="Bold"
                         FontSize="14" >
                <ListBox ItemsSource="{Binding probClasser/LstProbName}"></ListBox>
            </TabItem>
        </TabControl>

和c#部分

    /// <summary>
    /// Liste des problème pour BINDING avec les titres.
    /// </summary>
    public static ObservableCollection<ProbDiffList> probClasser;

    public MainWindow()
    {
        InitializeComponent();
        DataContext = probClasser;
    }

    /// <summary>
    /// Affichera la liste des Sudokus à résoudre classé par catégorie.
    /// </summary>
    /// <param name="argProb">List niveau List infoProb.</param>
    public void AfficheChoixProblème(List<ProbDiffList> argProb)
    {
        probClasser = new ObservableCollection<ProbDiffList>();
        GamesList.Visibility = Visibility.Visible;
        foreach (ProbDiffList uneListeParDiff in argProb)
        {
            probClasser.Add(uneListeParDiff);
        }
    }

显示 Expected result

解决方法

您应该绑定TabControl的ItemsSource,而不是显式创建TabItem,而是设置ItemTemplate和ContentTemplate:

<TabControl ItemsSource="{Binding}">
    <TabControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding NiveauProb}"/>
        </DataTemplate>
    </TabControl.ItemTemplate>
    <TabControl.ContentTemplate>
        <DataTemplate>
            <ListBox ItemsSource="{Binding LstProbName}"/>
        </DataTemplate>
    </TabControl.ContentTemplate>
</TabControl>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。