wpf : Bind to a control in another xaml file

扶醉桌前 提交于 2019-12-13 02:35:25

问题


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')

回答1:


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.



来源:https://stackoverflow.com/questions/31049845/wpf-bind-to-a-control-in-another-xaml-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!