2017-02-01 60 views
1

WPF級聯組合框我有一個自定義控制,如下與LINQ

<Label Grid.Row="12" Grid.Column="0" Name="lblCombobox1"> 
    Select value from Combobox1 
</Label> 
<ComboBox Grid.Row="12" Grid.Column="1" Name="cbxCombobox1" 
     SelectionChanged="cbxCostCentre_SelectionChanged" /> 
<Label Grid.Row="13" Grid.Column="0" Name="lblCombobox2"> 
    Select value from Combobox2</Label> 
<ComboBox Grid.Row="13" Grid.Column="1" Name="cbxCombobox2"/> 

一些組合框我使用一個主窗口,如下

<StackPanel Background="LightCyan"> 
<views:NewAccount HorizontalAlignment="Center" 
    Margin="30" FontSize="14"/> 

我這種自定義控件需要將組合框填充級聯以將先前的組合框選定值作爲下一個組合框的過濾參數。 看起來下面的代碼可以做到這一點。它正在進行過濾,爲Combobox2提供一系列值。但是,我可能錯過了LINQ查詢,如果我用T-SQL運行它,「where」子句提供的結果是不同的。這是非常相似的,但Combobox2中的一些或多或少的值與T-SQL列表不同。

using System.Linq; 
namespace AccountsSetup.UserControls 
{ 
    public partial class NewAccount : UserControl 
    { 
     public NewAccount() 
     { 
      InitializeComponent(); 

      using (SQL.DBDataContext db = new SQL.DBDataContext()) 
      { 
       var allCombobox1s = from t in db.Table1 
            select t.Name; 
       cbxCombobox1.ItemsSource = allCombobox1s; 
      } 
     } 

     private void cbxCombobox1_SelectionChanged(object sender, SelectionChangedEventArgs e) 
     {    
      using (SQL.DBDataContext dbs = new SQL.DBDataContext()) 
      { 
       string value = ""; 
       if (cbxCombobox1.SelectedIndex >= 0) 
        value = cbxCombobox1.SelectionBoxItem.ToString(); 
       var allCombobox2s = (from t in dbs.View1 
             where t.Combobox1.Contains(value) 
             select t.Name).Distinct(); 
       cbxCombobox2.ItemsSource = allCombobox2s; 

      } 

我曾嘗試將Combobox2更改爲以下代碼。但是,這是相同的結果。

<ComboBox Grid.Row="13" Grid.Column="1" x:Name="cbxCombobox2" 
    ItemsSource="{Binding}" SelectedValue="{Binding ElementName=cbxCombobox1, 
    Path=SelectedItem.Name, Mode=OneWay}" /> 

請指出可以在代碼中進行哪些更正。

感謝

+0

有什麼TSQL和'View1'表看起來像?究竟有什麼區別? –

+0

'cbxCombobox1.ItemsSource = allCombobox1s'應該讀取'cbxCombobox1.ItemsSource = allCombobox1s.ToList()'。同樣,'cbxCombobox2.ItemsSource = allCombobox2s;'應該是'cbxCombobox2.ItemsSource = allCombobox2s.ToList();' – MickyD

+0

感謝您的更正建議添加.ToList()。我做的。 儘管View1中存在所有字段,但我使用Table1的原因是View1中的一個字段是Table1中的一個字段。然而,我也可以從View1中獲得它。 – user5237764

回答

0

你應該比較視圖名稱列的值第一ComboBox的SelectedItem屬性的值。

試試這個:

private void cbxCombobox1_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    using (SQL.DBDataContext dbs = new SQL.DBDataContext()) 
    { 
     string value = cbxCombobox1.SelectedItem as string; 
     if (!string.IsNullOrEmpty(value)) 
     { 
      var allCombobox2s = (from t in dbs.View1 
           where t.Name != null && t.Name.Contains(value) 
           select t.Name).Distinct().ToList(); 
      cbxCombobox2.ItemsSource = allCombobox2s; 
     } 
    } 
} 
+0

非常感謝。現在它工作得很好! – user5237764

+0

不客氣,但請記住接受答案:http://meta.stackexchange.com/questions/23138/how-to-accept-the-answer-on-stack-overflow – mm8