簡體   English   中英

將UserControl的ListBox的ItemSource綁定到父DataContext時出錯

[英]Error on binding UserControl's ListBox's ItemSource to parent DataContext

我試圖將UserControl的ListBox綁定到父級ViewModel的公共列表。
在這里,我將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 Name="lbConfigurationList" ItemsSource="{Binding Test}">

由於MainWindow具有_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中的新增功能。如果使用的是語言的早期版本,則必須使用后備字段或在構造函數中進行設置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM