C# 如何在多重绑定中设置路径

C# 如何在多重绑定中设置路径,c#,wpf,C#,Wpf,UserControl中combobox(“CB2”)的ItemsSource需要绑定到通过字典与combobox CB1中选择的键对应的值(字符串列表)。在这个测试用例中,dictionary是viewmodel“TestDic”中的一个属性,我可以使用多重绑定来实现这一点。下面的代码运行良好,结果符合预期,combobox 2会正确更新 <StackPanel> <ComboBox Name="CB1" ItemsSource="{Bind

UserControl中combobox(“CB2”)的ItemsSource需要绑定到通过字典与combobox CB1中选择的键对应的值(字符串列表)。在这个测试用例中,dictionary是viewmodel“TestDic”中的一个属性,我可以使用多重绑定来实现这一点。下面的代码运行良好,结果符合预期,combobox 2会正确更新

<StackPanel>
  <ComboBox Name="CB1" ItemsSource="{Binding  Source={x:Static local:Data.TheAcademicUnit},Path=Subjects}" SelectedValue="{Binding Subject}" />
  <ComboBox Name="CB2">
     <ComboBox.ItemsSource>
         <MultiBinding>
            <MultiBinding.Converter>
              <local:SubjectToCodesConverter/>
            </MultiBinding.Converter>
           <Binding Path="TestDic"/>
           <Binding Path="Subject" />
          </MultiBinding> 
      </ComboBox.ItemsSource>
  </ComboBox>
</StackPanel>

但是,如果我需要指定到TestDic的不同路径,该怎么办?在应用程序中,这些都将包装在listview数据模板中,因此我必须以不同的方式指定TestDic的路径。我需要像这样的东西

<Binding Path="{Binding DataContext.TestDic, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"/>

但这(毫不奇怪)不起作用,错误为System.Windows.Markup.XamlParseException:“无法在类型为“Binding”的“Path”属性上设置“Binding”。“绑定”只能在DependencyObject的DependencyProperty上设置。”

我如何克服这个“两条路”的问题(如果这确实是个问题的话)。下面是转换器的参考,但我认为没有任何问题

public class SubjectToCodesConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (values != null && values.Length >= 2)
            {
                var myDict = values[0] as Dictionary<string,List<string>>;
                var myKey = values[1] as string;
                if (myDict != null && myKey != null)
                {
                    return myDict[myKey];
                }
            }
            return Binding.DoNothing;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotSupportedException();
        }
公共类SubjectToCodesConverter:IMultiValueConverter
{
公共对象转换(对象[]值,类型targetType,对象参数,System.Globalization.CultureInfo区域性)
{
如果(值!=null&&values.Length>=2)
{
var myDict=作为字典的值[0];
var myKey=字符串形式的值[1];
if(myDict!=null&&myKey!=null)
{
返回myDict[myKey];
}
}
不做任何事;
}
公共对象[]转换回(对象值,类型[]目标类型,对象参数,System.Globalization.CultureInfo区域性)
{
抛出新的NotSupportedException();
}

这回答了你的问题吗?这回答了你的问题吗?这回答了你的问题吗?我会看看。似乎比我想象的更复杂。绑定只是一个标记扩展。本质上只是一个用于创建BindingExpression的数据容器。在应用绑定之后(即在其上创建BindingExpression之后),禁止对其进行更改。因此,无法动态修改所使用的绑定实例。您需要想出一种不同的方法来解决您的问题。