[英]Bind IsEnabled property for Button in WPF
我有一个需要以编程方式启用/禁用的Button
。 我希望使用绑定到bool
来实现这一点。 这是Button XAML:
<Button x:Name="logInButton" Height="30" IsEnabled="{Binding IsLoggedIn}">
<Image Source="/images/img.png"></Image>
</Button>
这是被调用的代码:
public MainWindow()
{
InitializeComponent();
enabled = false;
}
private bool enabled;
public bool IsLoggedIn
{
get
{
return enabled;
}
set
{
enabled = value;
}
}
正确分配属性IsLoggedIn
的值。 但IsEnabled
没有分配我需要的值。 例如:
我尝试使用Binding Path
和Binding Source
设置值,但没有任何工作。
请告知可能出错的地方。
然后......我认为一定是这样。
class Model : INotifyPropertyChanged
{
public bool enabled;
public bool IsLoggedIn
{
get
{
return enabled;
}
set
{
enabled = value;
OnPropertyChanged("IsLoggedIn");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName]string property = "")
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
缺少两件事:
IsLoggedIn
属性应该在DataContext
对象中。 在MVVM中,这意味着它应该在视图模型中。 DataContext
应该实现INotifyPropertyChanged
以便在以编程方式更新属性时视图可以更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.