Question

I have a WPF TabControl like this one:

XAML:

<TabControl Name="myTabControl" ItemsSource="{Binding Main.TabItems, UpdateSourceTrigger=PropertyChanged}" />

Now I want to add TabItems at runtime. So here is my Model.

C#:

class Model() : INotifyPropertyChanged
{
    private List<TabItem> _tabitems = new List<TabItem>();

    public Model()
    {
        TabItem myItem = new TabItem();
        myItem.Header = "test";
        myItem.Content = "test";
        _tabitems.Add(myItem);
        TabItems = _tabitems;
    } 

    public List<TabItem> TabItems
    {
        get
        {
            return _tabitems;
        }
        set
        {
            _tabitems = value;
            OnPropertyChanged("TabItems");
        }
    }

    public bool Execute()
    {
        TabItem myItem = new TabItem();
        myItem.Header = "test";
        myItem.Content = test;
        _tabitems.Add(myItem);
        TabItems = _tabitems;

        return true;
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

If I start my programm the code in the constructor works well. I have one TabItem in the TabControl. But if i execute my function Execute() from a command then nothing happens. How can I solve the problem that i can add a tabitem out of the constructor. If I start the function in the constructor then it works.

Was it helpful?

Solution

Because the Xaml has no idea you added a new TabItem

Change your List<T> to ObservableCollection<T>, ObservableCollection's will notify the UI of any changes to the collection(Add, remove etc).

Example:

class Model : INotifyPropertyChanged
{
    private ObservableCollection<TabItem> _tabitems = new ObservableCollection<TabItem>();

    public Model()
    {
        TabItem myItem = new TabItem();
        myItem.Header = "test";
        myItem.Content = "test";
        TabItems.Add(myItem);
    } 

    public ObservableCollection<TabItem> TabItems
    {
        get
        {
            return _tabitems;
        }
        set
        {
            _tabitems = value;
            OnPropertyChanged("TabItems");
        }
    }

    public bool Execute()
    {
        TabItem myItem = new TabItem();
        myItem.Header = "test";
        myItem.Content = test;
        TabItems.Add(myItem);

        return true;
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top