简体   繁体   English

WPF:绑定到模式父窗口中的datacontext

[英]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? 从PropertiesTablesWindow.xaml中可以绑定到主窗口的DataContext吗? 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: 主窗口DataContext具有属性EditMode,它使我知道程序是否处于编辑模式,该模式又将使子窗口上的DataGrid变为只读或可编辑状态,如下所示:

            <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. 我已经尝试了窗口和应用程序的AncestorType,但显然这些不起作用。

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. 当然,您也可以构建一个中介程序来存储上下文,但是第一个解决方案是如此诱人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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