【问题标题】:Checked ListBox (WPF)选中的列表框 (WPF)
【发布时间】:2011-12-29 13:42:07
【问题描述】:

我无法让已选中的ListBox 工作。

我的业务对象(它是一个私有/嵌套类,因此是小写的)

    class shop : System.ComponentModel.INotifyPropertyChanged
    {
        internal int id;
        string _name;
        internal string name
        {
            get { return _name; }
            set
            {
                _name = value;
                if (PropertyChanged != null) PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs("name"));
            }
        }

        bool _selected;
        internal bool selected
        {
            get { return _selected; }
            set
            {
                _selected = value;
                if (PropertyChanged != null) PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs("selected"));
            }
        }
    }

我的 XAML:

<ListBox ItemsSource="{Binding}" Grid.Row="1" HorizontalAlignment="Stretch" Margin="10,0,10,0" Name="lbSelectedShops" VerticalAlignment="Stretch">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <CheckBox Width="Auto" Content="{Binding Path=name}" IsChecked="{Binding Path=selected, Mode=TwoWay}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>                                
</ListBox>

后面代码中的数据绑定非常简单:

lbSelectedShops.ItemsSource = _shops;

其中_shopsObservableCollection&lt;shop&gt;(包含两个元素)。

我得到的是列表框中的两个 空白 复选框(没有标题,并且都勾选了,即使 selectedItemsSource 中的所有项目设置为 true)。

我已经很沮丧了,我敢肯定这一定是一件非常微不足道的事情。这里有什么问题?

【问题讨论】:

  • 你只能绑定到公共属性,所以如果你的类是嵌套的和私有的,我认为这不会起作用。您可以查看 Visual Studio 中的“输出”窗口以了解绑定失败的位置。

标签: wpf data-binding checkbox listbox c#-3.0


【解决方案1】:

它不起作用,因为您的属性是内部属性,并且对于数据绑定,您需要公共属性。
来自 MSDN (Binding Sources Overview):

您可以绑定到公共属性、子属性以及 任何公共语言运行时 (CLR) 对象的索引器。绑定 引擎使用 CLR 反射来获取属性的值。 或者,实现 ICustomTypeDescriptor 或具有 注册的 TypeDescriptionProvider 也可以与绑定引擎一起使用。

【讨论】:

  • 没错:谢谢! (我不会想到 - 毕竟,列表框与 shop 类存在于同一个应用程序/命名空间中)。
【解决方案2】:

绑定仅适用于公共属性(和公共类)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多