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

wpf : Bind to a control in another xaml file

我有一个 main.xaml 文件。在 main.xaml 文件中,它引用另一个 xaml 文件中的列表框。使用view:LayoutViewList

调用

在main.xaml文件中,有一个按钮。只有当列表框被选中时,该按钮才会被启用。看起来 ElementName=view.LayoutViewList.LayoutListBox 不起作用。非常感谢

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

绑定错误:

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

如果带有 Binding 的视图是 MainView 文件的子视图,则需要使用 RelativeSource Binding。试试这个:

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

这个Binding指的是SelectedItems属性暴露的对象Count属性设置为名为 MainView.

UserControlWindowDataContext