使用MVVM模式時,在Loaded事件中設置與ComBox.SelectedItem關聯的屬性時不會觸發ComBox的SelectionChanged事件。
如何使頁面加載時觸發這一事件呢?可調用外部線程操作, 方法有二,1是使用timer類,2是使用Thread類。偽代碼如下:
private
void PageLoad(
object o)
{
_thisWindow = o as Window;
Thread t = new Thread( delegate()
{
_thisWindow.Dispatcher.Invoke( new Action( delegate()
{
PageLoad();
}));
});
t.Start();
}
private void PageLoad()
{
this.SeletcedItem = " ok ";
// do some thing...
{
_thisWindow = o as Window;
Thread t = new Thread( delegate()
{
_thisWindow.Dispatcher.Invoke( new Action( delegate()
{
PageLoad();
}));
});
t.Start();
}
private void PageLoad()
{
this.SeletcedItem = " ok ";
// do some thing...
}
另外,如果外部線程調用某個類,當這個類觸發某事件時,事件處理方法中一定要加上類似的語句:
Thread t =
new Thread(
delegate()
{
_thisWindow.Dispatcher.Invoke( new Action( delegate()
{
this.SeletcedItem = " ok ";
}));
});
{
_thisWindow.Dispatcher.Invoke( new Action( delegate()
{
this.SeletcedItem = " ok ";
}));
});
也就是Dispatcher.Invoke()方法,否則ComBox的SelectionChanged事件也無法觸發。
找到這些經驗,花了不少代價啊!!!
補充:
我找到出現開關所述問題的原因所在了,如果直接xaml中設置Combox.SelectionChanged="SelectionChanged",那么在Loaded時,SelectionChanged事件會正常觸發。
但我用的是Triggers:
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding ProvinceSelectionChangedCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
這樣在頁面加載的時候會沒有用。我猜是因為loaded時,Triggers還沒生效,也就是說要等頁面加載完畢Triggers才會被實例化。
我以前就有這種猜測,果然不出所料啊!這也是mvvm的一個弊端吧!