c# - 如何将 WPF 控件文本绑定(bind)到 bool 值,并在 xaml 中决定文本

标签 c# wpf mvvm

我在 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));
    }
}

上面代码中的OnPropertyChangedINotifyPropertyChangedPropertyChanged事件的方法实现。如果您使用任何框架或定义自己的名称,请将其替换为适当的名称。

您可以定义一个样式,例如:

<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 以更新 ButtonContent 属性这是值(value)。

还有一点,按钮样式继承自默认样式。如果您有任何 Keyed 样式,请在 BasedOn 属性中使用它。

关于c# - 如何将 WPF 控件文本绑定(bind)到 bool 值,并在 xaml 中决定文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50546342/

相关文章:

c# - 区分引用静态属性的两个调用程序集的最佳方法

c# - 责任绩效链

c# - 是否值得实现 IDataErrorInfo?

c# - 获取对 View 模型当前实例的引用

c# - 将 ObservableCollection 绑定(bind)到 ListBox 的选定项

c# - 为什么 sharpmap 在从点映射到多边形时返回不一致的结果?

c# - 使用矩形在图像上创建搜索区域

wpf - 如何在文本框上实现自动保存?

.net - 在 MVVM 模型下,鼠标位置相关的 Action 应该如何发生?

c# - 是否可以通过编程方式扩展 Azure 应用服务