重构绑定的创建,从基于代码隐藏到基于 XAML

Refactoring creation of a binding from code-behind based to XAML based

今天我使用构造函数接收数组,然后将其绑定到元素。

C#

public MyDialog(Stuff stuff, IEnumerable<Thing> things)
{
  InitializeComponent();
  DataContext = stuff;
  MyComboBox.SetBinding(ComboBox.ItemsSourceProperty, new Binding { Source = things });
  ShowDialog();
}

XAML

<ComboBox x:Name="MyComboBox"
          DisplayMemberPath="Canonic"
          Style="{StaticResource DefaultComboBoxStyle}" />

我想将其重构为完全基于 XAML 的方法,并且我已通过以下方式处理它。但是,我现在的组合框中没有任何值,而且我非常不确定如何解决它。

<ComboBox x:Name="MyComboBox"
          ItemsSource="{Binding 
            RelativeSource={
              RelativeSource FindAncestor,
              AncestorType={x:Type Window}},
            Path=DataContext.TheActualThings}"
          DisplayMemberPath="Canonic"
          Style="{StaticResource DefaultComboBoxStyle}" />-->

当然,class Things 包含许多字段,其中之一称为 Canonic 并包含一个要呈现为选项描述的字符串。创建对话框的控件是从 Window.

派生的 ProgramWindow 类型

请注意,有一个类似的问题(可能会出现),但不同之处在于,在另一个问题中,我遇到了语法问题,一旦问题得到解决,就会出现此处描述的实际技术问题。 (我没有给另一个问题 link 因为我不想影响它的观看次数。)

public partial class ProgramWindow : Window
{
  public ProgramWindow()
  {
    InitializeComponent();
    DataContext = new ViewModel();
  }

  private void DataGridRow_OnDoubleClick(Object sender, MouseButtonEventArgs eventArgs)
  {
    MyDialog dialog = new MyDialog(
      (sender as DataGridRow).Item as Stuff,
      (DataContext as ViewModel).TheActualThings);

    if (dialog.DialogResult ?? false) ...
    else ...
  }
}

问题是您正在尝试使用 RelativeSource 绑定访问另一个 WindowDataContextRelativeSource 绑定只能访问同一可视化树中的元素,而另一个 Window 不能以这种方式访问​​。