2013-04-24 31 views
0

我想將樣例數據中的數據綁定到c#中的代碼。當嘗試使用不同的在線模型時,我沒有得到確切的輸出。我想在數據表中的兩個值之間進行算術運算。

我的XML數據是這樣的:在xml數據的代碼中創建綁定

<SampleData:data xmlns:SampleData="clr-namespace:Expression.Blend.SampleData.data" 
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> 
    <SampleData:data.factors> 
     <SampleData:cfsItem col1="item1" item1="1" item2="2" /> 
     <SampleData:cfsItem col2="item2" item2="3" item2="4" /> 
    </SampleData:data.factors> 
</SampleData:data> 

我想選擇與LINQ查詢的價值;即從數據表中的「因素」中選擇col1,並將其與從listbox元素返回的值進行比較。

private void ListBox1_Tap(object sender, GestureEventArgs e) 
{ 
    ListBoxItem selected = ListBox1.SelectedItem as ListBoxItem; 
    string y = selected.Content as string; 
    this.DataContext = from factors in data 
         where col1.factors == y 
         select item1; 
} 

任何人都可以幫我解決這個問題嗎?謝謝!

+0

除非您告訴我們問題是什麼,否則我們無法幫助您。預期的結果是什麼,實際結果是什麼? – Patrick 2013-04-24 17:02:37

+0

我正在做轉換應用程序。我需要從列表框中選擇項目。它將作爲列表框中的選定項目被複制。這將與數據庫中的項目進行比較,並使用特定項目的LINQ查詢來選擇轉換因子。 – 2013-04-24 17:34:20

回答

0

它看起來像你的data對象是單個項目,並且你真的找factorsdata
根據您所展示的內容,您可能需要以下內容才能根據ListBox.SelectedItem的內容與col1屬性相比較來選擇factors

就像一個說明:我認爲你的意思是在第二個記錄中的第一個item2真的意味着item1。如果所以下面將適用:

private void ListBox1_Tap(object sender, GestureEventArgs e) 
{ 
    var selectedItem = (ListBoxItem)ListBox1.SelectedItem; 
    if (selectedItem != null) 
    { 
     var y = (string)selectedItem.Content; 
     var filteredFactors = (from factor in data.factors 
           where factor.col1 == y 
           select factor.Item1); 
     //filteredFactors is IEnumerable 
     this.DataContext = filteredFactors; 
     // if you need the first only or nothing if there is none. 
     this.DataContext = filteredFactors.FirstOrDefault(); 
     // if there can be nothing or only one 
     this.DataContext = filteredFactors.SingleOrDefault(); 
    } 
} 

在上面的例子我只選擇了過濾factorsitem1
如果要返回整個記錄,您將在查詢中刪除.item1

var filteredFactors = (from factor in data.factors 
         where factor.col1 == y 
         select factor); 



你可能會注意到我已經var多次使用的關鍵字。如果它提高可讀性,我喜歡使用它。如果您有興趣,請參閱Implicitly Typed Local Variables