这里有两件事,首先你应该理想地将属性声明为 a DependencyProperty
,这样你就可以绑定它并获得自动更改通知以在正确的时间更新 UI。然后,您需要更正绑定,使其指向在该UserCoontrol
级别声明的属性(正如您编写的那样,它绑定到DataContext
可能未设置的 .
试试这个,在 XAML 中:
<UserControl x:Class="WpfApplication1.TopBarUserControl"
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"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
x:Name="MainControl"> <!--Give a XAML name to the whole control to bind to properties declared in code-behind-->
<Menu Visibility="{Binding ElementName=MainControl, Path=MenuVisibility}"/>
</UserControl>
请注意,绑定在控制级别具有ElementName
匹配的。x:Name
将您的财产转换为DependencyProperty
:
using System.Windows;
using System.Windows.Controls;
namespace WpfApplication1
{
public partial class TopBarUserControl : UserControl
{
public static readonly DependencyProperty MenuVisibilityProperty = DependencyProperty.Register("MenuVisibility", typeof(Visibility), typeof(TopBarUserControl), null);
public Visibility MenuVisibility
{
get { return (Visibility)GetValue(MenuVisibilityProperty); }
set { SetValue(MenuVisibilityProperty, value); }
}
public TopBarUserControl()
{
InitializeComponent();
}
}
}