gpt4 book ai didi

c# - 在 WPF 中实现 CheckBoxes 的 ListBox

转载 作者:太空狗 更新时间:2023-10-29 18:35:52 26 4
gpt4 key购买 nike

提前致歉,因为我知道这个问题已经出现了好几次。但是,我正在努力确定我自己的代码哪里出错了。只是寻找复选框列表和旁边的名称。目前编译正常,但 ListBox 为空。

所有代码都在一个名为 ucDatabases 的控件中。

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#代码:

  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));
}
}

填充一些测试数据的辅助方法:

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);
}
}

非常感谢建议和解决方案!

最佳答案

public ObservableCollection<CheckBoxDatabase> Databases;是一个字段。

您应该将其替换为属性:

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

别忘了 INotifyPropertyChanged !

关于c# - 在 WPF 中实现 CheckBoxes 的 ListBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14673409/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com