【问题标题】:How to bind to the page from a child of a custom control如何从自定义控件的子级绑定到页面
【发布时间】:2013-06-07 15:57:16
【问题描述】:

我有以下自定义 Silverlight 面包屑控件:

    <custom:BreadcrumbList Navigator="{Binding ModuleNavigator}">
        <custom:BreadcrumbList.Items>
            <custom:BreadcrumbItem ViewName="Home"/>
            <custom:BreadcrumbItem ViewName="Items"/>
            <custom:BreadcrumbItem Command="{Binding ReturnCommand}"/>
            <custom:BreadcrumbItem ViewName="ItemConstraints"/>
        </custom:BreadcrumbList.Items>
    </custom:BreadcrumbList>

我真的希望BreadcrumbItemCommand 属性绑定到页面的数据上下文,而不是父控件。我知道如何使用 RelativeSource 绑定参数在其他 XAML 环境中执行此操作,但这在这里不起作用。我怎么能在 Silverlight 中做到这一点?

谢谢。

【问题讨论】:

    标签: silverlight binding


    【解决方案1】:

    我确实找到了解决方案,我仍在等待更好的解决方案。 BreadcrumbItem 直接子类DependencyObject。我添加了以下属性:

        private Object _parentContext = null;
    
        public Object ParentContext
        {
            get { return _parentContext; }
            set { _parentContext = value; RaisePropertyChanged("ParentContext"); }
        }
    

    然后在BreadcrumbList(父控件)的Loaded 事件中,我将所有项目ParentContext 属性设置为其数据上下文。

        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            Loaded -= OnLoaded;
    
            foreach (var item in Items.OfType<BreadcrumbItem>())
                item.ParentContext = DataContext;
        }
    

    然后我将我的 XAML 更改为:

    <custom:BreadcrumbList Navigator="{Binding ModuleNavigator}">
        <custom:BreadcrumbList.Items>
            <custom:BreadcrumbItem ViewName="Home"/>
            <custom:BreadcrumbItem ViewName="Items"/>
            <custom:BreadcrumbItem Command="{Binding ParentContext.ReturnCommand}"/>
            <custom:BreadcrumbItem ViewName="ItemConstraints"/>
        </custom:BreadcrumbList.Items>
    </custom:BreadcrumbList>
    

    这可行,但我仍在寻找更好的选择。

    【讨论】:

      【解决方案2】:

      根据您的数据上下文的级别,有几种方法。如果您要绑定到数据网格本身中的元素,那么您可以使用与父控件类型的祖先类型的相对源的绑定。 如果您有一个包含您要查找的数据的特定元素,则可以使用该元素名称和数据路径进行绑定。 如果您在 xaml 中声明了视图模型,则可以绑定到静态资源并使用视图模型的名称和数据项的路径。

      【讨论】:

      • 其中两个在 Silverlight 中不起作用。另一个并没有真正帮助我。我试图从内部元素(即BreadcrumbItem)中获取页面的数据上下文(我的视图模型)。还是谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-15
      • 1970-01-01
      • 2016-02-22
      • 2019-10-29
      • 1970-01-01
      • 2011-03-20
      • 2015-02-15
      相关资源
      最近更新 更多