在 WPF 中实现复选框列表框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14673409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Implementing a ListBox of CheckBoxes in WPF
提问by JBond
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!
建议和解决方案将不胜感激!
采纳答案by Federico Berasategui
public ObservableCollection<CheckBoxDatabase> Databases;is a field.
public ObservableCollection<CheckBoxDatabase> Databases;是一个字段。
You should replace it with a Property:
你应该用一个属性替换它:
public ObservableCollection<CheckBoxDatabase> Databases {get;set;};
public ObservableCollection<CheckBoxDatabase> Databases {get;set;};
Don't forget INotifyPropertyChanged!
不要忘记INotifyPropertyChanged!

