将绑定的创建从基于代码隐藏重构为基于XAML

本文关键字:代码 重构 XAML 隐藏 绑定 创建 于代码 | 更新日期: 2023-09-27 18:06:59

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

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}" />-->

当然,类Things包含许多字段,其中一个名为Canonic,包含一个字符串作为选项描述呈现。创建对话框的控件类型为ProgramWindow,派生自Window

请注意,有一个类似的问题,但不同之处在于,在另一个问题中,我有语法问题,一旦这个问题解决了,这里描述的实际技术问题就出现了。(我没有给出另一个问题的链接,因为我不想影响它的浏览量。)

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 ...
  }
}

将绑定的创建从基于代码隐藏重构为基于XAML

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