[英]Binding combobox to another combobox
將組合框綁定到另一個組合框時出現問題。 我正在嘗試將參數(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; }
}
可能嗎? 感謝您的任何答案!
我去年做的這是一個凌亂,幼稚的實現,似乎很奏效。 肯定有更好的出路。 我沒有嘗試在我的xaml中進行任何實際的綁定,而是創建了事件處理程序。 您可以為ComboBox創建事件處理程序,每當發送ComboBox失去焦點,關閉其DropDown,更改選擇等時便觸發該事件處理程序。
如果希望一個ComboBox依賴於另一個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映射到ComboBox的Dictionary或您發現合適的東西來執行此操作。 確定目標之后,您將清除先前添加的所有項目,然后使用新的項目重新填充。 下面是偽代碼中的一種方法(實際上)。
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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.