简体   繁体   中英

Error on binding UserControl's ListBox's ItemSource to parent DataContext

I'm trying to bind the ListBox of a UserControl to a public list of the parent's ViewModel.
Here I set the DataContext to the main window

public partial class MainWindow : Window
{
    private ConfigurationListViewModel _ConfList = new ConfigurationListViewModel();
    public MainWindow()
    {
        InitializeComponent();
        DataContext = _ConfList.ConfList;
    }
}

and the class is:

public class ConfigurationListViewModel
{
    public ConfigurationList ConfList = new ConfigurationList();
}

public class ConfigurationList
{
    public List<string> Test = new List<string>();

    public ConfigurationList()
    {
        Test.Add("aaa");
        Test.Add("bbb");
        Test.Add("ccc");
    }
 }

In the Main Window XAML I set the User Control:

<GroupBox Header="Configurations" >
    <local:ConfigurationMng x:Name="ConfigMng"/>
</GroupBox>

And in the ConfigurationMng I have the following ListBox, that I'm trying to bind to the List "Test".

<ListBox Name="lbConfigurationList" ItemsSource="{Binding Test}">

Since the MainWindow has _ConfList.ConfList 's DataContext, I thought that the ListBox had the scope of the List "Test"; but using the logger I get the following output:

System.Windows.Data Error: 40 : BindingExpression path error: 'Test' property not found on 'object' ''ConfigurationList' (HashCode=43536272)'. BindingExpression:Path=Test; DataItem='ConfigurationList' (HashCode=43536272); target element is 'ListBox' (Name='lbConfigurationList'); target property is 'ItemsSource' (type 'IEnumerable')

but I couldn't understand what error lies behind that.

What I'm missing?

Test in the ConfigurationList class is not a property, but a field. You can only bind to public properties .

Just change the initialization line to:

public List<String> Test {get; set;} = new List<string>();

Note that auto-property initializers are new in C# 6. You'll have to use a backing field or set it in the constructor if you are using an earlier version of the language.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM