今天我使用构造函数来接收一个数组,然后将它绑定到元素。
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,并包含一个要呈现为选项描述的字符串。创建对话框的控件是从Window派生的ProgramWindow类型。
请注意,有一个类似的问题(可能会出现),但不同之处在于,在另一个问题中,我遇到了语法问题,一旦解决,这里就会出现实际的技术问题。(我没有给出另一个问题的链接,因为我不想影响它的视图计数。)
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 ...
}
}