[英]CheckBox two way binding doesn't work
我想對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"}
};
}
}
最后我使用GridView綁定我的ProductList:
<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的行。 任何想法這個代碼有什么問題? 提前致謝!
要使雙向綁定工作,首先應在視圖模型和產品類中實現INotifyPropertyChanged
事件,以確保在屬性視圖中發生某些更改時立即通知
還要確保正確設置DataContext
視圖
view.DataContext = yourViewModel;
並且正如Fischermaen所提到的那樣你將無法調試這種屬性,如果你想調試你應該做這樣的事情
public class Product
{
private bool isSelected;
public bool IsSelected
{
get { return isSelected; }
set { isSelected = value; }
}
}
您將CheckBox綁定到IsSelected屬性。 此屬性實現為自動實現的屬性 。 你永遠不會在調試器中破壞setter或getter。 我在代碼中看不到任何問題,它應該像你編寫代碼一樣工作。
您應該在綁定類型的INotifyPropertyChanged
接口上實現,並且在設置 IsSelected
屬性時必須通知它。
來自msdn的文檔和示例:
http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.