【问题标题】:Implementing a ListBox of CheckBoxes in WPF在 WPF 中实现 CheckBox 的 ListBox
【发布时间】:2016-08-04 23:18:29
【问题描述】:

提前道歉,因为我知道这个问题已经出现了好几次。但是,我正在努力确定我自己的代码哪里出了问题。只是在它们旁边寻找复选框和名称的列表。目前编译正常,但 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);
        }
    }

建议和解决方案将不胜感激!

【问题讨论】:

  • 你在哪里实例化你的视图? DataContext 分配在哪里? Visual Studio 输出窗口中是否有任何绑定错误?
  • “数据库”字段在哪里?是在单独的类中还是在Window类中?
  • DataContext 当前设置为“this”。输出窗口中没有绑定错误,我不确定实例化视图是什么意思..对不起。 Databases 是 ucDatabases 中的类级变量。

标签: c# wpf listbox


【解决方案1】:

public ObservableCollection&lt;CheckBoxDatabase&gt; Databases; 是一个字段。

你应该用一个属性替换它:

public ObservableCollection&lt;CheckBoxDatabase&gt; Databases {get;set;};

别忘了INotifyPropertyChanged

【讨论】:

  • 这样一个简单的解决方案。那成功了。非常感谢!
  • “你用属性替换它”是“你应该替换它”啊哈。我的错。这就是当你在玩 DotA 时在 SO 和魔兽争霸 3 之间进行 alt-tab 时发生的情况哈哈。
猜你喜欢
  • 2011-01-04
  • 1970-01-01
  • 2011-05-01
  • 1970-01-01
  • 2011-05-20
  • 2022-07-20
  • 1970-01-01
  • 1970-01-01
  • 2019-03-19
相关资源
最近更新 更多