如何访问作为依赖项属性公开的 WPF 用户控件的子控件?



以前有人问过这个问题,但我没有找到满意的答案。假设你有一个像这样的UserControl

<UserControl x:Class="TestShowUserControl.UserControl1"
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:d="http://schemas.microsoft.com/expression/blend/2008" 
xmlns:local="clr-namespace:TestShowUserControl"
mc:Ignorable="d" 
d:DesignHeight="40" d:DesignWidth="200">
<d:DesignerProperties.DesignStyle>
<Style TargetType="UserControl">
<Setter Property="Background" Value="White"/>
</Style>
</d:DesignerProperties.DesignStyle>
<DockPanel>
<Label x:Name="lblCaption" DockPanel.Dock="Left" Content="Caption"/>
<TextBox Text="Hi there"/>
</DockPanel>

Label控件通过DependencyProperty暴露,如下所示:

public partial class UserControl1 : UserControl
{
#region DependencyProperties
public static readonly DependencyProperty MyCaptionControlProperty = DependencyProperty
.Register(nameof(MyCaptionControl),
typeof(Label),
typeof(UserControl1),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
#endregion
#region Properties
public Label MyCaptionControl
{
get { return (Label)GetValue(MyCaptionControlProperty); }
set { SetValue(MyCaptionControlProperty, value); }
}
#endregion
public UserControl1()
{
InitializeComponent();
MyCaptionControl = lblCaption;
}
}

我如何才能做到以下几点:

<local:UserControl1 MyCaptionControl.Visibility="Collapsed"/>

如果不可能,是否有其他方法可以在XAML中做到这一点?请注意,我想使用标签,就好像我自己在本地声明它一样,并且我希望能够在必要时将其内容绑定到ViewModel。尽管如此,必须暴露Style可能是没有更好解决方案的替代方案。

正如@mm8在评论中指出的那样,技术问题无关紧要,因为方法不正确。UserControl的目的是为某个任务提供一个可重用的接口。UserControl的消费者不应该知道它的组件,因为它们在未来可能会有所不同。现在,所谓的MyCaptionControlLabel类型,但它可以是TextBlock或其他类型。因此,这个问题被认为是有答案的。

最新更新