您的位置:首页 > 其它

WPF ItemsControl 的 ItemsSource 绑定的一个bug

2009-05-08 19:43 363 查看
不知道是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同步的.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: