WPF BoolToBrushConverter 返回 4 个值和 4 个画笔?

发布于 2024-09-26 14:38:08 字数 154 浏览 1 评论 0原文

我使用 BoolToBrushConverter 将 TextBox 的 Brush 属性绑定到 UserControl 中的 IsValid 依赖属性。我的 IsValid 需要 4 个状态,因为我需要 4 个不同的画笔从转换器返回。还有其他使用字符串的方法吗?而不是 bool ,这可以吗?

I bind a TextBox`s Brush Property to an IsValid Dependency Property in a UserControl with a BoolToBrushConverter. My IsValid would need 4 states because I need 4 different brushes to return from the converter. Is there another way using strings? instead of bool, could that work?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谷夏 2024-10-03 14:38:08

当然。您可以将任何您想要的内容转换为您想要的任何内容。您只需要实现它的转换方式如何

但是,如果状态数限制为 4,我建议使用 Enum 而不是字符串,因为这使得重构等方面更安全。

类似的东西应该有效:

internal enum State
{
    State1, State2, State3, State4
}

// ...

public void Convert(object value, ...)
{
    if (value is State)
    {
        State state = (State)value;
        switch(state)
        {
            case State.State1:
                return myBrush1;
            case State.State2:
                return myBrush2;
            case State.State3:
                return myBrush3;
            case State.State4:
                return myBrush4;
        }
    }

    return defaultBrush;
}

顺便说一句:根据情况,使用触发器可能会更好,但这并不总是可行。

Sure. You can convert whatever you want to whatever you want. You just need to implement the way how it is converted.

However, if the number of states is limited to 4, I would suggest using an Enum instead of strings because this makes it safer regarding refactoring etc.

Something like that should work:

internal enum State
{
    State1, State2, State3, State4
}

// ...

public void Convert(object value, ...)
{
    if (value is State)
    {
        State state = (State)value;
        switch(state)
        {
            case State.State1:
                return myBrush1;
            case State.State2:
                return myBrush2;
            case State.State3:
                return myBrush3;
            case State.State4:
                return myBrush4;
        }
    }

    return defaultBrush;
}

BTW: Depending on the scenario, it might be better to use triggers, but that is not always possible.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文