如何在我的自定义控制中更改儿童控制的可见性?
我继承了 HeaderedContentControl
的 Control
。当用户单击父控件时,我需要隐藏子控件,但我不知道如何访问其子控件。
这是我的代码。
public class MyHeaderedContentControl : HeaderedContentControl
{
public static readonly DependencyProperty ClickToHideProperty =
DependencyProperty.Register("ClickToHide", typeof(bool), typeof(MyHeaderedContentControl),
new PropertyMetadata(null));
public bool ClickToHide
{
get => (bool)GetValue(ClickToHideProperty);
set => SetValue(ClickToHideProperty, value);
}
protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e)
{
base.OnPreviewMouseLeftButtonDown(e);
//TODO Hide one child control when user clicked the parent control
e.Handled = true;
}
}
I inherited my Control
for HeaderedContentControl
. I need to hide the child control when user clicked the parent control, but I do not know how to access its child control.
Here is my code.
public class MyHeaderedContentControl : HeaderedContentControl
{
public static readonly DependencyProperty ClickToHideProperty =
DependencyProperty.Register("ClickToHide", typeof(bool), typeof(MyHeaderedContentControl),
new PropertyMetadata(null));
public bool ClickToHide
{
get => (bool)GetValue(ClickToHideProperty);
set => SetValue(ClickToHideProperty, value);
}
protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e)
{
base.OnPreviewMouseLeftButtonDown(e);
//TODO Hide one child control when user clicked the parent control
e.Handled = true;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以设置
子控件的可见性
,即内容
。
如果您创建自定义控件,则也可以指定
TemplatePart
对于ContentPresenter
。然后,您始终可以显示和隐藏显示Content
的ContentPresenter
,而不是依赖于实际的子控件。这也适用于非UIElement
子元素,例如string
。唯一的要求是您的控件模板包含这部分。
请参阅创建具有可自定义外观的控件以供参考。
You could set the
Visibility
of the child control, which is theContent
of the control.If you create a custom control, you could alternatively specify a
TemplatePart
for aContentPresenter
. Then you can always show and hide theContentPresenter
which shows theContent
, instead of depending on the actual child controls. This would also work for non-UIElement
children like astring
.The only requirement would be that your control template contains this part.
See Creating a Control That Has a Customizable Appearance for reference.