复选框双向绑定不起作用(CheckBox two way binding doesn't w

2019-09-28 17:42发布

我想提出两个办法对里面的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"}
                          };
    }
}

最后我有网格的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>

当我调试这个应用程序,当我选中/取消复选框从未到达二传手的路线。 任何想法是错误的代码? 提前致谢!

Answer 1:

您绑定的复选框IsSelected属性。 此属性是作为一个自动实现的属性 。 你永远不会在二传手断裂或调试器吸气剂。 我看不出任何问题,在你的代码,它应该像你编码它。



Answer 2:

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

另外,请确保您设置DataContext正确的观点

view.DataContext = yourViewModel;

和Fischermaen提到你不能,如果你想调试调试这样的属性,你应该做这样的事情

 public class Product
    {
        private bool isSelected;

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


Answer 3:

您应该实现绑定类型上INotifyPropertyChanged接口,并且如果当IsSelected propertyis 设置有通知了。

从MSDN文档和示例:

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



文章来源: CheckBox two way binding doesn't work