[英]Better approach for event when tabitem is selected
我有一個tabcontrol,其中有8個tabitems,里面有很多datagrids和listbox。 我只想在選擇一個特定的tabitem時啟動一個事件。
第一種方法是tabcontrol中的SelectionChanged,其中包含if語句
If ((thetabiwant!=null)&& (thetabiwant.IsSelected))
{
//code here
}
第二種方法是在所需的tabitem中有一個mouseup事件。
什么是最好的方法?
(起伏不定的是SelectionChanged因為datagrids而一直觸發,而mouseup事件解決方案並沒有讓我開心)
謝謝。
一般情況下,您不應過於擔心因為與您的條件不符而跳過的事件。 框架本身做了很多 ,你最終也會做很多事情(例如,當聽取INotifyPropertyChanged
事件時)。
在您的情況下,觸發的幾個額外的SelectionChanged
事件實際上可以忽略不計。 每個事件都要求用戶實際更改選項卡,這種情況不會經常發生。 另一方面,一旦你在你關心的標簽中,實際上發生了很多鼠標事件。 並不是說你需要關心它們的數量(除非你遇到問題,否則你真的不應該這樣)但當然你可以避免它。
所以在這種情況下,是的,只是跳過SelectionChanged
事件是最好的方法。
您還可以綁定IsSelected屬性
在集合中執行更改為true時需要執行的操作
<TabControl Grid.Row="0">
<TabItem Header="One" IsSelected="{Binding Path=Tab1Selected, Mode=TwoWay}"/>
<TabItem Header="Two" IsSelected="{Binding Path=Tab2Selected, Mode=TwoWay}"/>
</TabControl>
private bool tab1Selected = true;
private bool tab2Selected = false;
public bool Tab1Selected
{
get { return tab1Selected; }
set
{
if (tab1Selected == value) return;
tab1Selected = value;
NotifyPropertyChanged("Tab1Selected");
}
}
public bool Tab2Selected
{
get { return tab2Selected; }
set
{
if (tab2Selected == value) return;
tab2Selected = value;
if (tab2Selected)
{
MessageBox.Show("Tab2Selected");
// do your stuff here
}
NotifyPropertyChanged("Tab2Selected");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.