【问题标题】:CheckBox two way binding doesn't workCheckBox 双向绑定不起作用
【发布时间】:2011-12-27 08:44:45
【问题描述】:

我想对 ListView 中的复选框进行两种方式的绑定。这是我的产品类:

public class Product
{
    public bool IsSelected { get; set; }
    public string Name { get; set; }
}

在 ViewModel 类中,我有可观察到的产品集合:

    private ObservableCollection<Product> _productList;
    public ObservableCollection<Product> ProductList
    {
        get
        {
            return _productList;
        }
        set
        {
            _productList = value;
        }
    }

    public MainViewModel()
    {
        ProductList = new ObservableCollection<Product>
                          {
                              new Product {IsSelected = false, Name = "Not selected"},
                              new Product {IsSelected = true, Name = "Selected"},
                              new Product {IsSelected = true, Name = "Selected"}
                          };
    }
}

最后我有了绑定我的 ProductList 的 ListView 网格:

<Grid>
    <ListView Height="120" HorizontalAlignment="Left" 
                  VerticalAlignment="Top"
                  SelectionMode="Multiple" 
                  ItemsSource="{Binding ProductList}" >
        <ListView.View>
            <GridView>
                <GridViewColumn Width="40">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <CheckBox IsChecked="{Binding Path=IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <GridViewColumn Width="120" Header="Product Name" DisplayMemberBinding="{Binding Path=Name}" />
            </GridView>
        </ListView.View>
    </ListView>
</Grid>

当我调试这个应用程序时,当我选中/取消选中复选框时,它永远不会到达 setter 行。 任何想法这段代码有什么问题? 提前致谢!

【问题讨论】:

标签: c# wpf xaml data-binding wpf-controls


【解决方案1】:

要让两种方式绑定起作用,您首先应该在视图模型和产品类中实现INotifyPropertyChanged 事件,以确保在属性视图发生某些变化时立即得到通知

还要确保您正确设置 DataContext 的视图

view.DataContext = yourViewModel;

正如 Fischermaen 所提到的,您将无法调试此类属性,如果您想调试,您应该这样做

 public class Product
    {
        private bool isSelected;

        public bool IsSelected
        {
            get { return isSelected; }
            set { isSelected = value; }
        }
    }

【讨论】:

    【解决方案2】:

    您将 CheckBox 绑定到 IsSelected 属性。此属性实现为auto implemented property。您永远不会在调试器中的 setter 或 getter 处中断。我在您的代码中看不到任何问题,它应该像您编写的代码一样工作。

    【讨论】:

      【解决方案3】:

      您应该在绑定类型INotifyPropertyChanged 接口上实现,并且当IsSelected 属性设置时必须通知它。

      来自 msdn 的文档和示例:

      http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx

      【讨论】:

        猜你喜欢
        • 2019-11-13
        • 2012-02-14
        • 2019-03-05
        • 2014-04-10
        • 2011-10-14
        • 2014-03-12
        • 1970-01-01
        相关资源
        最近更新 更多