将组合框绑定到另一个组合框
我将组合框绑定到另一个组合框时存在问题。我试图从第一个组合框动态传递参数(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,更改选区等,就会触发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。
我认为这是我需要的。谢谢您的帮助 – Eluvium
它'不清楚。第二个组合框必须显示什么? Id,Name ...! – Amine
有几种IT服务。每项IT服务都有一些指标。我必须在第一个组合框IT服务中进行选择,并将其传递给方法GetMetricName(SelectedService),以便在所选(在第一个组合框)IT服务的第二个组合框度量标准中显示。 – Eluvium
显示名称,但选定的值必须是Id – Eluvium