Skip to main content
 首页 » 编程设计

c#之CheckBox 双向绑定(bind)不起作用

2024年02月23日1352php

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

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

最后我有了 Grid 和绑定(bind)了我的 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 的行。 知道这段代码有什么问题吗? 提前致谢!

请您参考如下方法:

要使双向绑定(bind)起作用,您应该首先在您的 View 模型和产品类中实现 INotifyPropertyChanged 事件,以确保在属性 View 发生某些更改时立即得到通知

还要确保正确设置 View 的 DataContext

view.DataContext = yourViewModel; 

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

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