Reputation: 17831
I want to get into DataBinding and currently I'm stuck. I just can't get it to work. I read many tutorials, but honestly, none of the really helped me. I know what DataBinding is and why it's cool to use it, but I never came across a tutorial that showed me what to do in my code. They all just assume I know what I have to do there and only show the XAML side.
This is my class:
public class Test : Window
{
public IList<String> data { get; set; }
public Test() {
data = new List<String>();
InitializeComponents();
data.Add("Hello");
data.Add("World");
}
}
And here's my XAML
<ListBox HorizontalAlignment="Left" Margin="6,6,0,6"
Name="SourceDocumentsList" Width="202"
ItemsSource="{Binding Source={x:Static Application.Current}, Path=data}" />
Yet, nothing is displayed when I render the window. How can something this easy fail? What am I doing wrong here?
The way I understand it, I tell the Listbox that it should bind itself to the data
property of the currently running application, which is my class Test
.
Upvotes: 0
Views: 166
Reputation: 657
Move those properties into a separate class like
public class ViewModel
{
public IList<String> Data { get; set; }
public ViewModel()
{
Data = new ObservableCollection<string>();
Data.Add("Hello");
Data.Add("World");
}
}
Change your Window Code Behind as
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
Your Xaml will look less complicated
<ListBox HorizontalAlignment="Left" Margin="6,6,0,6"
Name="SourceDocumentsList" Width="202"
ItemsSource="{Binding Data}" />
This is what we call moving into MVVM pattern. Happy Coding !
Upvotes: 1
Reputation: 185553
The currently running application is not that class, it's just a window, what you bind to is the instance of the App
class. You cannot statically get that window instance this way. How the binding should be made depends on where that XAML is (if it is in the Test
window you can for example use RelativeSource={RelativeSource AncestorType=Window}
instead).
I would recommend reading the MSDN documentation on data binding and this article on debugging.
Upvotes: 2