我有一个 UserControl,它包含 bool 属性 A。 在包含该 UserControl 的主窗口中,我必须根据 A 的值启用/禁用按钮。 我试图像这样将 A 设置为公开和绑定(bind)按钮:
<Button IsEnabled="{Binding MyUserControl.A}"/>
在 UserControl 中,我为 Property A 设置了 PropertyChangedEventHandler,例如:
private bool _a;
public bool A
{
get
{
return _a;
}
set
{
if (_a == value)
return
_a = value;
OnPropertyChanged("A");
}
}
看起来不错。但我不知道为什么它不起作用。 似乎我缺少一些在主窗口与其用户控件之间进行通信的实现(因为使用 OnPropertyChanged,用户控件内的所有绑定(bind)都可以正常工作)。
我有一些解决方案 1. 使用Messenger 从Usercontrol 发送消息,内容为A 的值,主控件将捕获并将值设置为按钮的IsEnabled。 2. 创建一个事件并在 A 的值发生变化时引发它。
您是否知道这个问题以及如何解决它? 您认为以下 2 种解决方案效果好还是您有任何其他建议?
感谢阅读。
< <编辑> > 这个问题解决了。在代码隐藏中设置用户控件的数据上下文是我的错误,并且没有意识到我已经在数据模板中设置了它们。 --> 因此,复制对用户控件的 View 模型进行了 2 次初始化。 --> 不知何故,它使 NotifyPropertyChange 无法正常工作。 编辑>
很抱歉这个问题的标题不适合这个愚蠢的错误。看来我以正确的方式解决了标题问题。 感谢您的阅读和建议。
请您参考如下方法:
在 wpf 中显示用户控件的替代方法。查看此 StackOverflow 讨论 here
替代 INotifyPropertyChanged :绑定(bind)的依赖属性。
//用户控件
public partial class UserControl1 : UserControl
{
public bool A
{
get { return (bool)GetValue(AProperty); }
set { SetValue(AProperty, value); }
}
public static readonly DependencyProperty AProperty =
DependencyProperty.Register("A", typeof(bool), typeof(UserControl1), new UIPropertyMetadata(false));
public UserControl1()
{
InitializeComponent();
DataContext = this;
}
}
//主窗口.xaml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:WpfApplication1"
Height="300" Width="300">
<StackPanel>
<src:UserControl1 x:Name="myControl" />
<Button IsEnabled="{Binding A, ElementName=myControl}" />
</StackPanel>
