WPF:绑定到一个控制在另一个XAML文件 [英] wpf : Bind to a control in another xaml file

查看:371
本文介绍了WPF:绑定到一个控制在另一个XAML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个main.xaml文件。在main.xaml文件,它是指一个列表框在另一个XAML文件。它是利用电话观点:LayoutViewList

在main.xaml文件,有一个按钮。选中列表框中的按钮将只启用。看起来像的ElementName = view.LayoutViewList.LayoutListBox是行不通的。非常感谢你。

 按钮IsEnabled ={绑定的ElementName =观点:LayoutViewList.LayoutListBox,路径= SelectedItems.Count}

绑定错误:

  System.Windows.Data错误:4:参考:LayoutViewList.LayoutListBox的ElementName =视图'绑定无法找到来源。 BindingEx pression:路径= SelectedItems.Count;的DataItem = NULL;目标元素是'按钮'(名称=''); target属性是IsEnabled(类型'布尔')
System.Windows.Data错误:4:无法与参考:LayoutViewList.LayoutListBox的ElementName =视图'绑定找到源头。 BindingEx pression:路径= SelectedIndex的;的DataItem = NULL;目标元素是'按钮'(名称=''); target属性是'NoTarget'(类型'对象')


解决方案

您需要使用<一个href=\"https://msdn.microsoft.com/en-us/library/system.windows.data.binding.relativesource(v=vs.110).aspx\"相对=nofollow> 的RelativeSource绑定 如果与绑定的观点是一个孩子的的MainView 文件。试试这个:

 &LT;按钮IsEnabled ={结合DataContext.SelectedItems.Count,的RelativeSource = {
    的RelativeSource AncestorType = {X:输入您的preFIX:的MainView}}/&GT;

绑定计数通过暴露对象的属性 SelectedItems 属性的在设置为的DataContext 的的用户控件窗口名为的MainView

I have a main.xaml file. In the main.xaml file, It refer to a listbox in another xaml file. It is call using view:LayoutViewList

In the main.xaml file, There is a button. The button will be enable only when listbox is selected. Look like ElementName=view.LayoutViewList.LayoutListBox is not working. Thank you very much

Button IsEnabled="{Binding ElementName=view:LayoutViewList.LayoutListBox, Path=SelectedItems.Count}" 

Binding error :

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=view:LayoutViewList.LayoutListBox'. BindingExpression:Path=SelectedItems.Count; DataItem=null; target element is 'Button' (Name=''); target property is 'IsEnabled' (type 'Boolean')
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=view:LayoutViewList.LayoutListBox'. BindingExpression:Path=SelectedIndex; DataItem=null; target element is 'Button' (Name=''); target property is 'NoTarget' (type 'Object')

解决方案

You need to use a RelativeSource Binding if the view with the Binding is a child of your MainView file. Try this:

<Button IsEnabled="{Binding DataContext.SelectedItems.Count, RelativeSource={
    RelativeSource AncestorType={x:Type YourPrefix:MainView}}" />

This Binding refers to the Count property of the object exposed by the SelectedItems property in the object that is set as the DataContext of the UserControl or Window named MainView.

这篇关于WPF:绑定到一个控制在另一个XAML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆