简体   繁体   中英

WPF: Bind to datacontext in modal parent window

I am opening a modal window using:

    public void PropertiesTablesButtonClicked(object sender, RoutedEventArgs e)
    {
        Window _childWindow = new PropertiesTablesWindow();

        // Assign MainWindow as the owner of this window, this will cause the MainWindow
        // to become inactive and make the child window flash if the main window is clicked
        _childWindow.Owner = App.Current.MainWindow;

        _childWindow.ShowDialog();
    }

Is there a way from within PropertiesTablesWindow.xaml to bind to the DataContext of the main window? The main window DataContext has a property EditMode which lets me know if the program is in edit mode which in turn would be used to make a DataGrid on the child window read-only or editable like so:

            <DataGrid Name="PropertiesDataGrid" 
                      ItemsSource="{Binding PropertiesDataView, UpdateSourceTrigger=PropertyChanged}"
                      SelectedItem="{Binding SelectedProperty, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                      AutoGenerateColumns="False"
                      CanUserAddRows="False"
                      MaxHeight="200"
                      IsReadOnly="{Binding RelativeSource={RelativeSource FindAncestor, 
                                          AncestorType={x:Type Application}}, Path=DataContext.EditMode, 
                                          UpdateSourceTrigger=PropertyChanged,
                                          Converter={StaticResource NegatedStringComparisonToBooleanConverter}, ConverterParameter=Admin}">

I have tried AncestorType of Window and Application but obviously these do not work.

Different windows have different visual trees. That's why you failed with the bindings. But why not to set the modal window's datacontext on the datacontext of the owner window? It'd do the trick. Of course you could also build a mediator to store the context but the first solution is so tempting simple.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM