我在 WPF 应用程序中有一个按钮控件,用于登录目的。该按钮有双重用途:注销时,应显示文本“登录”。登录时,应显示“注销”字样。
我可以通过数据绑定(bind)到 View 模型中适当的字符串属性来做到这一点。 但是,如果我可以简单地将数据绑定(bind)到“loggedIn” bool 值(注销为 false,登录为 true),然后决定在 View 中的按钮上显示什么文本,那就更好了。
这可能吗?
最佳答案
您可以使用 Xaml
中的 Style
实现它,而无需编写特定的 C# 代码。
假设您在 ViewModel
中有 IsLoggedIn
属性,该属性在按钮绑定(bind)命令的执行方法中被更改:
private void MyButtonCommandExecuteMethod()
{
this.IsLoggedIn = !this.IsLoggedIn;
}
private bool isLoggedIn;
public bool IsLoggedIn
{
get
{
return this.isLoggedIn;
}
set
{
this.isLoggedIn = value;
OnPropertyChanged(nameof(IsLoggedIn));
}
}
上面代码中的OnPropertyChanged
是INotifyPropertyChanged
的PropertyChanged
事件的方法实现。如果您使用任何框架或定义自己的名称,请将其替换为适当的名称。
您可以定义一个样式,例如:
<Button Command="{Binding YourButtonCommand}">
<Button.Style>
<Style TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
<Setter Property="Content" Value="Log In" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsLoggedIn}" Value="True">
<Setter Property="Content" Value="Log out" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
在上面的代码中,IsLoggedIn
绑定(bind)到 DataTrigger
以更新 Button
的 Content
属性这是值(value)。
还有一点,按钮样式继承自默认样式。如果您有任何 Keyed 样式,请在 BasedOn
属性中使用它。
关于c# - 如何将 WPF 控件文本绑定(bind)到 bool 值,并在 xaml 中决定文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50546342/