2016-10-17 58 views
0

一個布爾值,我怎樣才能讓謂語從異步方法C#做謂語返回從異步方法C#

private void OnFilterTextBoxTextChangedHandler(object oSender, TextChangedEventArgs oArgs) 
{ 
//Other operations 
_oCollectionView.Filter = new Predicate<object>(DoFilter); //wrong return type 
} 

返回一個布爾值返回方法

private async Task<bool> DoFilter(object oObject) 
{ 
    if (_sFilterText == "") 
    { 
     return true; 
    } 
    return false; 
} 
+0

你的'DoFilter'不是'async'方法。它缺乏「等待」。 –

+0

即使在DoFilter方法中等待,DoFilter方法仍未被等待iteslf,所以返回類型仍然是任務對不對? –

+0

@DovydasSopa即使我讓它等待它不能解決我的問題。 – user6384353

回答

0

Predicate<T>是一個代表。在向CollectionView添加過濾器時,不需要實例化新的謂詞。相反,你可以添加你的過濾器是這樣的:

_oCollectionView.Filter = DoFilter; 

二,CollectionView.Filter委託的簽名是public delegate bool Predicate<object>(object obj)。參數obj是正在評估的CollectionView的元素。您不能更改此簽名以使其異步。

在你的榜樣,我想看看執行以下操作:

constructor() 
{ 
    InitializeComponent(); 
    // Alternatively put this in an initialization method. 
    _oCollectionView.Filter = DoFilter; 
} 

private async void OnFilterTextBoxTextChangedHandler(object oSender, TextChangedEventArgs oArgs) 
{ 
    // Other operations 

    // Asynchronous processing 
    await SetupFilterAsync(); 
    _oCollectionView.Refresh(); 
} 

private async Task SetupFilterAsync() 
{ 
    // Do whatever you need to do async. 
} 

private bool DoFilter(object obj) 
{ 
    // Cast object to the type your CollectionView is holding 
    var myObj = (MyType) obj; 
    // Determine whether that element should be filtered 
    return myObj.ShouldBeFiltered; 
} 

您也可以定義過濾器,作爲一個lambda,這應該是這樣的,消除doFilter方法:

_oCollectionView.Filter = x => ((MyType)x).ShouldBeFiltered;