Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting ItemsSource of ListBox to a property of it's containing class

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?

like image 706
atiyar Avatar asked Dec 18 '25 15:12

atiyar


1 Answers

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.

like image 106
nemesv Avatar answered Dec 21 '25 03:12

nemesv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!