Не удалось привязать TabControl к ObservableCollection

Я ищу другой подобный вопрос, и я все еще не могу привязать свою коллекцию к TabControl. Мне удалось программно добавить заголовки и контент. Но я хотел бы использовать DataBinding

Я определил структуру со свойствами. Я вставляю его в общедоступную ObservableCollection и пытаюсь привязать коллекцию к TabControl.

Вот код С# для структуры

   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>

и часть С#

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

Это должно отображать ожидаемый результат


person Boucourt    schedule 20.08.2020    source источник
comment
1. DataContext кажется неправильным. Попробуйте удалить его. 2. probClasser — это поле, вы можете привязать его только к свойствам. 3. А почему probClasser статичен?   -  person Klaus Gütter    schedule 20.08.2020


Ответы (1)


Вы должны привязать ItemsSource TabControl и вместо явного создания TabItems установить 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>
person Clemens    schedule 20.08.2020
comment
Спасибо, это работает, когда я использую ItemTemplate и удаляю DataContext, как это было предложено @KlausGutter. - person Boucourt; 20.08.2020
comment
Конечно, вместо того, чтобы устанавливать DataContext (в строку) в XAML, просто привяжите ItemsSource к DataContext, установленному в коде позади. - person Clemens; 21.08.2020