0

I have a WPF app with a MainWindow. The MainWindow consists of several CLR properties of type ObservableCollection. The MainWindow has a datagrid, whose ItemsSource property is bound to one of the observable collections (works fine). Next, I have a dialog. Its purpose is to display one of the observable collections from the main window in a datagrid. The dialog gets instantiated in the MainWindow. Initially I was passing the ObservableCollection to the dialog's constructor, and copying it into the dialog's CLR property. Then I would set the DataContext of the dialog to itself, and bind the ItemsSource property in the datagrid to the name of the CLR property. This worked fine.

Is there a better way to do this instead of passing the observable collection through the constructor? I tried setting the ItemsSource property of the Datagrid in the dialog to the observable collection in the MainWindow by using the GUI editor, which generated a binding using RelativeAncestor, but the data did not show. The problem is I have a bunch of dialogs that are meant to display data from the MainWindow, and I feel like there should be a simpler solution rather than passing everything to dialog's constructor. Also, would the dialogs be considered SubViews? The main window is a view.

4

1 回答 1

1

假设您的Dialog控件已命名,并且在其代码中定义了DialogControl一个DependencyProperty命名。Items在 XAML 中,我会将此属性绑定到DataGrid这样的:

<DataGrid ItemsSource="{Binding Items, RelativeSource={RelativeSource Mode=
FindAncestor, AncestorType={x:Type DialogControl}}" />

RelativeSource绑定将关闭并搜索您的DialogControl类的属性并找到该Items属性。注意:不要将 的 设置DataContextUserControl自身。

现在在MainWindow.xaml.cs你实例化你的文件中DialogControl,你可以设置Items属性:

DialogControl dialogControl = new DialogControl();
dialogControl.Items = someCollection;
dialogControl.Show();

更新>>>

哦,我知道你现在在追求什么......你想从你的文件绑定UserControl到文件中的实际集合MainWindow.xaml.cs。你仍然可以听从我的建议,但是你需要把它放在你的文件中,而不是DependencyProperty放在你的文件中。在这种情况下,您的绑定将是:DialogControlMainWindow.xaml.csUserControl

<DataGrid ItemsSource="{Binding Items, RelativeSource={RelativeSource Mode=
FindAncestor, AncestorType={x:Type MainWindow}}" />

为此,该Items属性必须DependencyProperty.

于 2013-08-29T15:55:17.230 回答