将UserControl's ListBox's ItemSource绑定到父DataContext时出
本文关键字:DataContext 时出 ListBox UserControl ItemSource 绑定 | 更新日期: 2023-09-27 18:09:49
我试图将UserControl的ListBox绑定到父视图模型的公共列表。
这里我将DataContext设置为主窗口
public partial class MainWindow : Window
{
private ConfigurationListViewModel _ConfList = new ConfigurationListViewModel();
public MainWindow()
{
InitializeComponent();
DataContext = _ConfList.ConfList;
}
}
,类是:
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");
}
}
在主窗口XAML中我设置了用户控件:
<GroupBox Header="Configurations" >
<local:ConfigurationMng x:Name="ConfigMng"/>
</GroupBox>
在ConfigurationMng中,我有以下ListBox,我试图绑定到列表"Test"。
<ListBox Name="lbConfigurationList" ItemsSource="{Binding Test}">
由于主窗口有_ConfList.ConfList
的DataContext,我认为ListBox具有列表"Test"的范围;但是使用记录器,我得到以下输出:
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')
但我不明白这背后是什么错误。
我错过了什么?
ConfigurationList
类中的Test
不是属性,而是字段。只能绑定公共属性。
将初始化行改为:
public List<String> Test {get; set;} = new List<string>();
注意,自动属性初始化器在c# 6中是新的。如果您使用的是该语言的早期版本,则必须使用后备字段或在构造函数中设置它。