C# wpf 绑定到一个绑定

C# wpf binding to a binding

我正在为 c# wpf 编写问卷库。 在其中我有一个名为 MultipleChoiceOptionUserControl。它具有 DependencyProperty OptionType.

如果 OptionType 是 "combobox" 我插入一个组合框。

我希望能够将组合框的 ItemsSource 绑定到 MultipleChoiceOption 的 DependencyProperty,所​​以我创建了这个:

public static readonly DependencyProperty MultipleChoiceComboBoxItemsProperty = 
        DependencyProperty.Register("ComboBoxItems", typeof(List<string>), typeof(MultipleChoiceOption));

...

public List<string> OptionText
    {
        get { return GetValue(MultipleChoiceOptionTextProperty) as List<string>; }
        set { SetValue(MultipleChoiceOptionTextProperty, value); }
    }

如果 optionType 是 "combobox" 我添加一个组合框并设置这样的绑定:

 case "combobox":
                var combobox = new ComboBox
                {
                    HorizontalAlignment = HorizontalAlignment.Right
                };

                var b = new Binding()
                {
                    Path = new PropertyPath(MultipleChoiceComboBoxItemsProperty),
                    Source = ComboBoxItems
                };

                combobox.SetBinding(ComboBox.ItemsSourceProperty, b);

                combobox.SelectionChanged += ComboBoxChanged;
                stackPanel.Children.Add(textBlock);
                stackPanel.Children.Add(combobox);
                container.Children.Add(stackPanel);
                break;

在我的演示应用程序中,我尝试将绑定设置为 List<string>:

<wpfQuestionnaire:MultipleChoiceQuestion
                    QuestionNumber="2.1"
                    QuestionText="What friuts do you like the most of the following?">

                    <wpfQuestionnaire:MultipleChoiceOption
                        OptionType="combobox"
                        ComboBoxItems="{Binding RelativeSource={
                                            RelativeSource 
                                            Mode=FindAncestor,
                                            AncestorType={x:Type Window}},
                                        Path=QuestionTwoOneOptions,
                                        Mode=TwoWay}"/>

</wpfQuestionnaire:MultipleChoiceQuestion>

后面的代码:

  public partial class MainWindow : INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();
        Loaded += OnLoaded;
    }

    private void OnLoaded(object sender, RoutedEventArgs e)
    {
        MyQuestionnaire.QuestionnaireSubmitted += OnSubmitted;
        QuestionTwoOneOptions = new List<string>
            {
                "Apple",
                "Orange",
                "Pear"
            };
    }

    private List<string> _questionTowOneOptions;

    public event PropertyChangedEventHandler PropertyChanged;


    protected virtual void OnPropertyChanged(string property)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
    }

    private void OnSubmitted(object sender, QuestionnaireSubmittedEventArgs e)
    {
        foreach (var a in e.AllAnswers)
        {
               Debug.WriteLine(a.Answer);
        }
    }

    public List<string> QuestionTwoOneOptions
    {
        get { return _questionTowOneOptions; }
        set
        {
            _questionTowOneOptions = value;
            OnPropertyChanged(nameof(QuestionTwoOneOptions));
        }
    }

}

这会导致以下错误:

System.Windows.Data Error: 17 : Cannot get 'ComboBoxItems' value (type 'List`1') from '' (type 'List`1'). BindingExpression:Path=(0); DataItem='List`1' (HashCode=23674331); target element is 'ComboBox' (Name=''); target property is 'ItemsSource' (type 'IEnumerable') InvalidCastException:'System.InvalidCastException: Unable to cast object of type 'System.Collections.Generic.List`1[System.String]' to type 'System.Windows.DependencyObject'.

我不明白为什么要将列表转换为 DependencyObject。 我想我对使用什么类型有点困惑 go get a List<T> --> DependencyProperty --> ItemsSource.

之间的绑定

您创建的绑定 b 转到 ComboBoxItems 中的 属性 MultipleChoiceComboBoxItemsProperty,这是一个 List<string>,因此显然没有所需的属性。尝试解决此 DependencyProperty,必须将 Source 强制转换为 DependencyObject,这会导致错误。

使用Source = this应该可以解决问题。