views:

206

answers:

2

Hi how can i bind to this observablecollection

(Mainpage.xaml.cs)

public ObservableCollection tabs = new ObservableCollection();

in xaml? I've tried

(Mainpage.xaml)

But without any luck

A: 

Use WPF's binding syntax for XAML.

<YourControl ItemSource="{Binding tabs} />

You also need to set the DataContext of the top level control (grid, canvas etc) to be a type that owns the tabs collection (that type in the case you didn't rename your window's class, would be Window1.

So, for example, combining that with the XAML fragment above:

    <Grid DataContext="Window1">
....
....
        <YourControl ItemSource="{Binding tabs} />
....
....
    </Grid>  
Pierreten
sorry, wasn't aware that it got filtered out my xaml. That's what I tried, but didn't show the right stuff. Weird thing is that if i bind from codebehind.tabcontrol.itemssource = tabs;it works fine. For the neatness though,I don't like binding in code-behind
Jakob
A: 

a common pattern would be to set a datacontext in you loaded event, assuming you want to bind it to a TabControl called tabs_control on your page:

public MainPage()
{
    InitializeComponent();
    Loaded += OnLoaded;
}

protected void OnLoaded(obejct sender, RoutedEventArgs e)
{
    //Initialize tabs collection
    tab_control.ItemsSource = tabs;
}

Obviously you should substitute the actually control you want to bind to.

EDIT

Base on your comments, what you could do is just setup the control to be the data context, then your XAML binding should work. so instead of above you would do this:

protected void OnLoaded(obejct sender, RoutedEventArgs e)
{
    this.DataContext = this;
}

then in your XAMl you could do this:

<TabControl ItemsSource={Binding tabs} ... />
luke
thank you - I just thought it was best practice to do that in xaml, but I think I'll go with the code-behind itemssource binding then.
Jakob
why the downvote, please?
luke

related questions