[英]Binding Button.IsEnabled to Boolean Property
我有一个布尔属性,它查看多个复选框,如果选中其中任何一个,则返回true。 如果要选中任何复选框,我想启用一个按钮(属性返回true)。
目前,我有以下内容:
数据上下文集
public MainWindow() { InitializeComponent(); this.DataContext = this; }
按钮绑定集
<Button Name="button" IsEnabled="{Binding ButtonEnabled}">Apply</Button>
物业
public bool ButtonEnabled { get { if(checkboxes_enabled) return true; else return false; } }
我已经验证了该属性正在按预期进行更新,因此将其缩小为一个具有约束力的问题。 我还尝试了按钮内的数据触发器:
<Button Name="button" Content="Apply">
<Button.Style>
<Style TargetType="{x:Type Button}">
<Style.Triggers>
<DataTrigger Binding="{Binding ButtonEnabled}" Value="True">
<Setter Property="IsEnabled" Value="True"/>
</DataTrigger>
<DataTrigger Binding="{Binding ButtonEnabled}" Value="False">
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
两件事情:
如果要对绑定的属性进行更新,则需要INotifyPropertyChanged
。
public class MyClass
{
private bool _buttonEnabled;
public bool ButtonEnabled
{
get
{
return _buttonEnabled;
}
set
{
_buttonEnabled = value;
OnPropertyChanged();
}
}
public SetButtonEnabled()
{
ButtonEnabled = checkboxes_enabled;
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged<T>([CallerMemberName]string caller = null)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(caller));
}
}
}
您也不应有两个触发器,而应使用默认值。
<Button Name="button" Content="Apply">
<Button.Style>
<Style TargetType="{x:Type Button}">
<Setter Property="IsEnabled" Value="True"/>
<Style.Triggers>
<DataTrigger Binding="{Binding ButtonEnabled}" Value="False">
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
您需要添加以下代码以实现INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
然后从属性设置器调用OnPropertyChanged
我建议将按钮绑定到命令,而不是事件,这样,您可以将命令的“ canexecute”属性设置为false并禁用整个命令,该命令将为您自动禁用按钮。
我建议使用下面的教程,以更好地了解WPF命令以及如何使用它们,一旦您了解了它们的工作原理,我就会发现它们非常有用。
http://www.codeproject.com/Articles/274982/Commands-in-MVVM#hdiw1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.