user3753452
user3753452

Reputation: 139

wpf : Bind to a control in another xaml file

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

Upvotes: 1

Views: 4178

Answers (1)

Sheridan
Sheridan

Reputation: 69959

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.

Upvotes: 2

Related Questions