Question

I have the following xaml -

<Window x:Class="DataTemplateTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="400" Width="600" Loaded="Window_Loaded">    
    <Grid>
        <ListBox Height="380" Margin="10,12,0,0" Width="355"/>
    </Grid>
</Window>  

and the following code-behind -

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        _nameList = new List<string>
                        {
                            "X",
                            "Y",
                            "Z"
                        };
    }

    private List<string> _nameList;
    public List<string> NameList
    {
        get { return _nameList; }
    }
}  

I want to set the NameList as the ItemsSource of the ListBox from the xaml, not from the code-behind. How do I do that?

EDIT : I know the MVVM-way of doing this. But that's not what I'm asking.

EDIT : It's not that I don't like MVVM or so. While doing some quick test I just realized that I don't know how to do this. So, wondering if it's possible, and trying to learn. Is it anyhow possible using StaticResource?

Was it helpful?

Solution

If you've meant on "not doing the MVVM-way" that you don't want to use ViewModels then you can data-bind to the "codebehind" with the following steps:

Set the binding in XAML:

<ListBox ItemSource="{Binding NameList}"/>

And set the DataContext to this after you have populated your list e.g in the Window_Loaded event:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    _nameList = new List<string>
                    {
                        "X",
                        "Y",
                        "Z"
                    };
    DataContext = this;
}

Edit: If you don't want to set the DataContext you can bind directly to the window:

<Window Name="window" ... />

  <ListBox  ItemsSource="{Binding NameList, ElementName=window}"/>

Or you can use AncestorBinding as

<ListBox ItemsSource="{Binding NameList, RelativeSource={RelativeSource AncestorType=Window}}"/>

However I both cases the list will be empty because the view won't be notified by the fact that you populated your list in the loaded event. So you need to use INPC to notify that the "NameList" property changed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top