2016-04-28 146 views
0

我將組合框綁定到另一個組合框時存在問題。我試圖從第一個組合框動態傳遞參數(id)到啓動第二個組合框的方法。例如,如果我在第一個組合框中選擇第一個項目,則第二個組合框將使用從第一個組合框中選擇的參數進行初始化。將組合框綁定到另一個組合框

XAML:

<ComboBox Name="ItServiceCmbox" ItemsSource="{Binding ItServiceMetricsNames}" DisplayMemberPath="ServiceName" SelectedValuePath="ServiceId" /> 
<ComboBox Name="MetricCmbox" ItemsSource="{Binding SelectedItem.MetricId, ElementName=ItServiceCmbox}" DisplayMemberPath="MetricName" SelectedValuePath="MetricId"/> 

C#:

public partial class MainWindow : Window 
{ 
    readonly MetricsValuesHelper _metricsValuesHelper = new MetricsValuesHelper(new Repository()); 
    public static int SelectedService; 
    public static int SelectedMetric; 
    public ObservableCollection<ItServiceMetricsNames> ItServiceMetricsNames { get; set; }  

    public MainWindow() 
    { 
     InitializeComponent(); 
     this.DataContext = this; 
     SelectedService = Convert.ToInt32(ItServiceCmbox.SelectedItem); 
     ItServiceMetricsNames = new ObservableCollection<ItServiceMetricsNames>(); 
     ItServiceMetricsNames.Add(new ItServiceMetricsNames() 
     { 
      ServiceId = _metricsValuesHelper.GetServiceId(), 
      ServiceName = _metricsValuesHelper.GetServiceName(), 
      MetricId = _metricsValuesHelper.GetMetricId(SelectedService), 
      MetricName = _metricsValuesHelper.GetMetricName(SelectedService) 
     }); 
    } 
} 

而且ItServiceMetricsNames類:

public class ItServiceMetricsNames 
{ 
    public List<int> ServiceId { get; set; } 
    public List<string> ServiceName { get; set; } 
    public List<int> MetricId { get; set; } 
    public List<string> MetricName { get; set; } 
} 

這可能嗎?感謝任何答案!

+0

它'不清楚。第二個組合框必須顯示什麼? Id,Name ...! – Amine

+0

有幾種IT服務。每項IT服務都有一些指標。我必須在第一個組合框IT服務中進行選擇,並將其傳遞給方法GetMetricName(SelectedService),以便在所選(在第一個組合框)IT服務的第二個組合框度量標準中顯示。 – Eluvium

+0

顯示名稱,但選定的值必須是Id – Eluvium

回答

1

這是一個凌亂的,天真的實現,我去年做了,似乎工作。那裏肯定有更好的方法。而不是嘗試在我的xaml中做任何實際的綁定,我做了事件處理程序。您可以爲ComboBox創建事件處理程序,只要發送ComboBox失去焦點,關閉它的DropDown,更改選區等,就會觸發ComboBoxes。

如果您希望一個ComboBox依賴於另一個ComboBox,則可以使依賴ComboBox處於禁用狀態,直到選擇爲在獨立的ComboBox中製作。一旦做出選擇,您就可以使用適當的數據填充並啓用相關的組合框。

在你的代碼的事件處理程序會是這個樣子:

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) 
    { 
     // Independent ComboBox is the sender here 
     ProcessComboBoxes(sender as ComboBox); 
    } 

的ProcessComboBoxes方法取決於你想做什麼看起來不同。但是,本質上,它將識別您想要有條件地填充的目標/依賴組合框 - 使用從ComboBox映射到ComboBox的字典或您找到的適合的東西來執行此操作。識別目標後,您將清除之前添加的任何項目,然後重新填充新項目。下面是一個僞代碼(實際上)的方法。

private void ProcessComboBoxes(ComboBox senderBox) 
    { 
     ComboBox dependentBox = lookupDependent[senderBox]; 

     var itemType = itemTypes[senderBox.selectedIndex]; 
     var listOfItemsNeeded = lookupItemsByType[itemType]; 
     dependentBox.Items.Clear(); 

     foreach (string item in listOfItemsNeeded){ 
      dependentBox.Items.Add(item); 
     } 

     dependentBox.IsEnabled = true; 
    } 

不要忘記將您的事件處理程序添加到您的xaml中。確保密切關注事件的調用層次結構,並確定何時需要重新填充依賴的ComboBox。

+0

我認爲這是我需要的。謝謝您的幫助 – Eluvium