[英]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.