Tôi có một căn bản UserControl
mà bộ DataContext
của mình cho bản thân để dễ ràng buộc:DataContext Thiết trong UserControl đang ảnh hưởng đến các ràng buộc trong mẹ
<UserControl x:Class="MyControlLib.ChildControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
</UserControl>
này được sử dụng trong một tập tin mẹ XAML như thế này:
<UserControl x:Class="MyControlLib.ParentControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ctrl="clr-namespace:MyControlLib">
<ctrl:ChildControl x:Name="ChildName"
PropertyOnChild="{Binding PropertyInParentContext}"/>
</UserControl>
Vì một lý do nào đó, điều này đưa ra một lỗi ràng buộc dường như chỉ ra rằng DataContext
của điều khiển chính bị ảnh hưởng bởi thiết lập điều khiển con của riêng thiết bị DataContext
.
System.Windows.Data Error: 40 : BindingExpression path error: 'PropertyInParentContext' property not found on 'object' ''ChildControl' (Name='ChildName')'. BindingExpression:Path=PropertyInParentContext; DataItem='ChildControl' (Name='ChildName'); target element is 'ChildControl' (Name='ChildName'); target property is 'PropertyOnChild' (type 'whatever')
Tại sao "PropertyInParentContext" đang tìm kiếm trong kiểm soát trẻ em chứ không phải trong phụ huynh DataContext
?
Nếu tôi loại bỏ các
DataContext="{Binding RelativeSource={RelativeSource Self}}
từ sự kiểm soát trẻ em, sau đó mọi thứ hoạt động như thế nào tôi mong đợi.
Tôi có thiếu điều gì đó hiển nhiên ở đây không?
Cảm ơn, tôi đã hiểu lầm phạm vi của các ràng buộc và bài viết của bạn giải thích nó khá tốt. Tôi đã nghĩ rằng XAML của một UserControl là tự chứa, giống như trong một mẫu, nhưng tôi đoán đó là tất cả chỉ là một phần của tài liệu. – GazTheDestroyer