Skip to main content
 首页 » 编程设计

c#之Prism v4,MEF WPF 数据绑定(bind)

2024年02月23日13lidabo

首先,关于数据绑定(bind)的几个问题:

  • 是否将控件的默认 DataContext 设置为代码隐藏?例如,如果我在 test.xaml.cs 中有一个变量 orderNumber,我可以像在 xaml {Binding orderNumber} 中那样引用它吗?
  • 我只能对对象的属性进行数据绑定(bind)是否正确?

我在一个单独的模块/程序集中有一个 Prism 服务,我通过 MEF 将其导入到我的 Shell 应用程序中。我正在尝试对其进行数据绑定(bind),但它似乎不起作用。

我的解决方法如下。 在我的 Shell.xaml.cs 中:

[Import(AllowRecomposition = false)] 
private IRibbonService _menuService; 
public IRibbonService MenuService 
{ 
    get 
    { 
        return _menuService; 
    } 
} 
 
 
public void OnImportsSatisfied() 
{ 
    Debug.WriteLine("Imports satisfied", "Prism"); 
    this._moduleManager.LoadModuleCompleted += new EventHandler<LoadModuleCompletedEventArgs>(moduleManager_LoadModuleCompleted); 
 
    //TODO figure out how to properly bind to the ribbon 
    Ribbon.DataContext = _menuService; 
    RibbonAppMenu.DataContext = _menuService.ApplicationMenuData; 
} 

有没有办法在设置对象之前在 xaml 中设置数据上下文 - 特别是关于 MEF/Prism 场景?在我的功能区对象上,我尝试了 DataContext="{Binding MenuService}" 但这没有用。

请您参考如下方法:

Is the default DataContext for a control set to the codebehind? For example, if I have a variable orderNumber in test.xaml.cs, can I just reference it like so in the xaml {Binding orderNumber}?

没有。默认情况下,没有 DataContext,它使用 WPF 中的层次结构机制从父级继承。如果您希望控件具有一个控件,则需要显式设置该控件的 DataContext。

Is it correct that I can only databind to properties of an object?

是的。您只能绑定(bind)到属性。如果您希望双向绑定(bind)起作用,该对象还必须是 DependencyObject 或实现 INotifyPropertyChanged。

Is there a way to set the datacontext in xaml prior to an object being set - specifically in regards to MEF / Prism scenario? On my ribbon object I tried DataContext="{Binding MenuService}" but that didn't work.

这将尝试使用层次结构将 DataContext 设置为包含 DataContext 的 MenuService 属性(即:父控件/窗口的 DataContext 的 MenuService 属性)。您无法绑定(bind)自己来设置 DataContext。

您可以在 XAML 中创建一个新对象用作 DataContext,或者让一个包含对象为您提供 DataContext。