2011-12-27 125 views
1

我想为ListView内的复选框进行双向绑定。这是我的产品类别:CheckBox双向绑定不起作用

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

最后,我有网格,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的行。 任何想法这段代码有什么问题? 在此先感谢!

+0

http://stackoverflow.com/a/504936/440030 – 2011-12-27 08:49:15

回答

1

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

2

对于双向绑定工作,你首先应该实现INotifyPropertyChanged事件在您的视图模型和产品类别,以确保当有物业鉴于一些变化立即通知

还要确保您设置DataContext观点正确

view.DataContext = yourViewModel; 

和Fischermaen提到你将无法调试这样的财产,如果你想调试

public class Product 
    { 
     private bool isSelected; 

     public bool IsSelected 
     { 
      get { return isSelected; } 
      set { isSelected = value; } 
     } 
    } 
你应该做这样的事情