我有ObservableCollection和WPF ListBox来相互绑定。 我想在添加ObservableCollection时同时在Listbox中显示芯片位置。
<Window x:Class="Apeiron.ZoneSetter.ZoneSetterWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="765" Width="765">
<Grid>
<ListBox Name="lbPosList" ItemsSource="{Binding }" ></ListBox>
</Grid>
</Window>
案例1)效果很好。更改ObservableCollection时,它会在ListBox显示chnaged chip pos。
public partial class ZoneSetterWindow : Window, INotifyPropertyChanged
{
public ZoneSetterWindow()
{
InitializeComponent();
lbChipList.DataContext = SelectedZoneChipList;
}
public void AddChip(ZoneMapChipInfo chip)
{
if (!m_SelectedChipDic.ContainsKey(chip.Point))
{
m_SelectedChipDic.Add(chip.ChipPos, chip);
m_selectedzonechiplist.Add(chip);
}
}
private Dictionary<Point, ZoneMapChipInfo> m_SelectedChipDic = new Dictionary<Point, ZoneMapChipInfo>();
private ObservableCollection<ZoneMapChipInfo> m_selectedzonechiplist = new ObservableCollection<ZoneMapChipInfo>();
public ObservableCollection<ZoneMapChipInfo> SelectedZoneChipList
{
get
{
return m_selectedzonechiplist;
}
}
}
案例2)它不起作用。虽然ObservableCollection已更改,但它不会在ListBox中显示chnaged chip pos。
public partial class ZoneSetterWindow : Window, INotifyPropertyChanged
{
public ZoneSetterWindow()
{
InitializeComponent();
lbChipList.DataContext = SelectedZoneChipList;
}
public void AddChip(ZoneMapChipInfo chip)
{
if (!m_SelectedChipDic.ContainsKey(chip.Point))
{
m_SelectedChipDic.Add(chip.ChipPos, chip);
m_selectedzonechiplist.Add(chip);
}
}
private Dictionary<Point, ZoneMapChipInfo> m_SelectedChipDic = new Dictionary<Point, ZoneMapChipInfo>();
private ObservableCollection<ZoneMapChipInfo> m_selectedzonechiplist = new ObservableCollection<ZoneMapChipInfo>();
public ObservableCollection<ZoneMapChipInfo> SelectedZoneChipList
{
get
{
ObservableCollection<WaferZoneMapChipInfo> result = new ObservableCollection<WaferZoneMapChipInfo>();
foreach (ZoneMapChipInfo info in m_SelectedChipDic.Values)
{
result.Add(info);
}
return result;
}
}
}
我想始终同步m_SelectedChipDic和SelectedZoneChipList, 并在ListBox中显示SelectedZoneChipList的ChipPosition。
我不知道上述两种情况的区别。
是否有人了解我的上述问题。谢谢!!
答案 0 :(得分:1)
您的问题是,在您的第一个方法SelectedZoneChipList
返回列表视图然后绑定的m_selectedzonechiplist
。这就是为什么在向该列表添加内容时更新UI的原因。在您的第二种方法中,SelectedZoneChipList
会返回与m_selectedzonechiplist
无关的全新列表。因此,当您向m_selectedzonechiplist
添加内容时,不会发生任何事情,因为ListBox
绑定到一个完全不同的对象。
与ListBox
的绑定大致如下:
DataContext
一次。CollectionChanged
已更改的事件处理程序(ObservableCollection
已实现)。 更新:关于I want to synchronize m_SelectedChipDic and SelectedZoneChipList always
:您可以摆脱ObservableCollection
并将m_SelectedChipDic
设为ObservableDictionary并绑定您的ListView
{1}}改为那个。