简体   繁体   English

在WPF中实现CheckBoxes的ListBox

[英]Implementing a ListBox of CheckBoxes in WPF

Apologies in advance as i'm aware this question has appeared several times. 事先道歉,因为我知道这个问题多次出现过。 However, i'm struggling to identify where i'm going wrong with my own code. 但是,我正在努力找出我自己的代码出错的地方。 Just looking for a list of checkboxes and names next to them. 只需查找旁边的复选框和名称列表。 Currently it compiles ok but the ListBox is empty. 目前它编译好,但ListBox为空。

All of the code is within a control called ucDatabases. 所有代码都在一个名为ucDatabases的控件中。

XAML: XAML:

<ListBox Grid.Row="4" ItemsSource="{Binding Databases}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <CheckBox Content="{Binding Name}" IsChecked="{Binding IsChecked}" Margin="5 5 0 0"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

C# Code: C#代码:

  public ObservableCollection<CheckBoxDatabase> Databases;

public class CheckBoxDatabase : INotifyPropertyChanged
        {
            private string name;
            private bool isChecked;
            public Database Database;

            public bool IsChecked
            {
                get { return isChecked; }
                set
                {
                    isChecked = value;
                    NotifyPropertyChanged("IsChecked");
                }
            }

            public string Name
            {
                get { return name; }
                set
                {
                    name = value;
                    NotifyPropertyChanged("Name");
                }
            }

            public event PropertyChangedEventHandler PropertyChanged;
            protected void NotifyPropertyChanged(string strPropertyName)
            {
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs(strPropertyName));
            }
        }

Helper method to populate some test data: 帮助方法填充一些测试数据:

private void SetTestData()
    {
        const string dbAlias = "Database ";
        Databases = new ObservableCollection<CheckBoxDatabase>();
        for (int i = 0; i <= 4; i++)
        {
            var db = new Database(string.Format(dbAlias + "{0}", i));
            var newCBDB = new CheckBoxDatabase {Database = db, IsChecked = false, Name = db.Name};

            Databases.Add(newCBDB);
        }
    }

Advice and a solution would be much appreciated! 建议和解决方案将不胜感激!

public ObservableCollection<CheckBoxDatabase> Databases; is a field. 是一个领域。

You should replace it with a Property: 您应该用属性替换它:

public ObservableCollection<CheckBoxDatabase> Databases {get;set;};

Don't forget INotifyPropertyChanged ! 别忘了INotifyPropertyChanged

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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