How to bind to observable collection in code-behind from xaml
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 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(object 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} ... />
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>
精彩评论