zoukankan      html  css  js  c++  java
  • WPF ItemsControl 的 ItemsSource 绑定的一个bug

    不知道是Bug还是什么, 碰到这个问题的.

    我测试了一下,所有ItemsControls子类都有这个问题. 譬如: ComboBox

    public class NameValue
    {
        public object Value { get; set; }
        public string Name { get; set; }
    }

    public class TestObj: INotifyPropertyChanged

    {

        public event PropertyChangedEventHandler PropertyChanged;
        protected void Notify(string propName)
        {
            if (this.PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propName));
            }
        }

        int _v1;
        public int V1{

            get{ return _v1;}

            set{

               if (this._v1== value) { return; }
                    this._v1= value;
                    Notify("V1");

            }

        }

        int _v2;
        public int V2{

            get{ return _v2;}

            set{

               if (this._v2== value) { return; }
                    this._v2= value;
                    Notify("V2");

            }

        }

    }

    初始化List

    List<NameValue> lst = new List<NameValue>();

    lst.Add(new NameValue(){Name=”item1”, Value=”1”});

    lst.Add(new NameValue(){Name=”item2”, Value=”2”});

    lst.Add(new NameValue(){Name=”item3”, Value=”3”});

    绑定到ComboBox

    cbo1.ItemsSource = lst;

    cbo2.ItemsSource = lst;

    dataGrid.DataContext = new TestObj(){

        V1 = 1,

        V2 = 2

    };

    xaml代码

    <Grid x:Name="dataGrid">

    <ComboBox x:Name="cbo1" DisplayMemberPath="Name" SelectedValuePath="Value"  Width="80" IsSynchronizedWithCurrentItem="True"  SelectedValue="{Binding Path=V1}"/>

    <ComboBox x:Name="cbo2" DisplayMemberPath="Name" SelectedValuePath="Value"  Width="80" IsSynchronizedWithCurrentItem="True" SelectedValue="{Binding Path=V2}"/>

    </Grid>

    测试看看, 结果竟然是cbo1和cbo2联动了

    解决办法

    cbo1.ItemsSource = lst.ToArray();

    cbo2.ItemsSource = lst.ToArray();

    dataGrid.DataContext = new TestObj(){

        V1 = 1,

        V2 = 2

    };

    ItemsSource 指向了同一个List导致select同步了, 通过ToArray()方法,其实clone了2个NameValue数组实例, 这样就不会产生select同步的.

  • 相关阅读:
    成为Java GC专家系列(3) — 如何优化Java垃圾回收机制
    成为JavaGC专家Part II — 如何监控Java垃圾回收机制
    JAVA缓存的实现
    Lock Less Java Object Pool
    跟屌丝大哥学习设计模式--享元模式
    数据库 -- 由数据库连接池引出的三种设计模式
    优秀博客推荐:各种数据结构与算法知识入门经典
    学习总结
    洛谷P3360偷天换日(树形DP)
    疯子的算法总结14--ST算法(区间最值)
  • 原文地址:https://www.cnblogs.com/yinpengxiang/p/1452859.html
Copyright © 2011-2022 走看看