简体   繁体   English

wpf:绑定到另一个xaml文件中的控件

[英]wpf : Bind to a control in another xaml file

I have a main.xaml file. 我有一个main.xaml文件。 In the main.xaml file, It refer to a listbox in another xaml file. 在main.xaml文件中,它引用另一个xaml文件中的列表框。 It is call using view:LayoutViewList 使用view:LayoutViewList进行调用

In the main.xaml file, There is a button. 在main.xaml文件中,有一个按钮。 The button will be enable only when listbox is selected. 仅当选择列表框时,该按钮才会启用。 Look like ElementName=view.LayoutViewList.LayoutListBox is not working. 看起来ElementName = view.LayoutViewList.LayoutListBox无法正常工作。 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. 你需要使用RelativeSource Binding如果与视图Binding是你的孩子MainView文件。 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 . Binding引用由对象中的SelectedItems属性公开的对象的Count属性,该对象设置为名为MainViewUserControlWindow DataContext

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

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