![](/img/trans.png)
[英]How to access a DependencyProperty of child user control in WPF/MVVM?
[英]How do I access a WPF UserControl's child control exposed as DependencyProperty?
以前有人問過這個問題,但我沒有找到滿意的答案。 假設您有這樣的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 中是否有其他方法可以做到這一點? 請注意,我想使用 Label,就好像我自己在本地聲明它一樣,並且我希望能夠根據需要將其內容綁定到 ViewModel。 盡管如此,不得不公開Style
可能是沒有更好解決方案的替代方案。
正如@mm8 在評論中指出的那樣,技術問題不相關,因為方法不正確。 UserControl
的目的是為特定任務提供可重用的接口。 UserControl
的使用者不應該知道它的組件,因為它們將來會發生變化。 現在所謂的MyCaptionControl
是Label
類型,但它可以是TextBlock
或其他類型。 因此,該問題被視為已回答。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.