c# - Change the string at the end of System.Drawing.Color.<string> in Blazor - Stack Overflow

admin2025-04-18  2

I want to change the color mentioned at the end of the color names. For example, if we have System.Drawing.Color.Red I want to pass a string variable to change the Red to say, Pink or Orange after a user types it in an input field and presses a button. So System.Drawing.Color.(variable)

How do I do that?

This will be used to make an xml Component attribute as below:

<ComponentName color="System.Drawing.Color.(variable)" />

How can I do this?

I want to change the color mentioned at the end of the color names. For example, if we have System.Drawing.Color.Red I want to pass a string variable to change the Red to say, Pink or Orange after a user types it in an input field and presses a button. So System.Drawing.Color.(variable)

How do I do that?

This will be used to make an xml Component attribute as below:

<ComponentName color="System.Drawing.Color.(variable)" />

How can I do this?

Share Improve this question edited Jan 30 at 16:12 Joel Coehoorn 417k114 gold badges578 silver badges815 bronze badges asked Jan 30 at 16:04 dezdez 11 bronze badge 3
  • 1 Adding a string input to an XML attribute is easy. The question is, how are you generating the xml? How much do you want to validate the user input is a real color first, and what do you want to do if it fails? We can't help much until we know those things. Don't worry if the question ends up closed. Edit the question to add that information and it can be re-opened to give you a good answer. – Joel Coehoorn Commented Jan 30 at 16:14
  • What are you trying to do and why are you trying to hard-code the color, instead of using styles and classes? Browsers don't know anything about System.Drawing.Color so your own code will have to translate this to something the browser understands. ASP.NET Core apps that use Bootstrap do know about text-alert and text-info though. – Panagiotis Kanavos Commented Feb 12 at 10:23
  • Another problem is that Blazor won't detect changes to variable. If you absolutely must use Color, bind to a property or field whose type is Color – Panagiotis Kanavos Commented Feb 12 at 10:27
Add a comment  | 

2 Answers 2

Reset to default 0

You can't do that to begin with. You can bind the color attribute to a field or property whose value is the desired `Color. Or you can use a function that returns the desired color, eg:

<ComponentName color="@variable" />

@code 
{

    System.Drawing.Color variable...;
}

Of course it's better to use a better name. Using a field or property like this means Blazor can detect changes and auto-update too.

@using System.Drawing;

<ComponentName color="@_color" />

@code 
{

    Color _color=Color.Black;

    private async Task OnSomethingOrOther()
    {
        ...
        _color=Color.Red;
    }
}

That's not a great solution though. Browsers don't know what System.Drawing.Color. They do know about classes and styles, especially when frameworks like Bootstrap are used. It's better to use text-info or text-danger than hard-code colors.

In one of my components I use this code to display messages during and after an upload.

    <div class="col-3">

        <InputFile OnChange="@OnInputFileChange"/>
    </div>
    <div class="col-auto">
        @if (_loading)
        {
            <LoadingSpinner></LoadingSpinner>
        }
        else if (HasMessage)
        {
            <Alert Color="@(_error != null ? Color.Danger : Color.Success)" Visible="true">
                <AlertDescription >
                    @(_error ?? _message)
                </AlertDescription>
            </Alert>
        }
    </div>

Notice that the Color values are Danger and Success, not hard-coded values. This code uses Blazorise for the alert but InputFile is the built-in ASP.NET Core InputFile. The Color class is a record that specifies classes like primary,secondary etc not hard-coded colors.

The OnFileInputChange method just sets the fields :


bool _loading = false;

string _error = "";
string _message = "";

private async Task OnInputFileChange(InputFileChangeEventArgs e)
{
    _error = "";
    _message = "";
    _loading = true;


    try
    {
        ...
        _loading = false;
        var response = await Http.PostAsync(...);
        response.EnsureSuccessStatusCode();
        ..
        _message = "Some OK message";
    }
    catch (HeaderValidationException exc)
    {
        var sb = new StringBuilder("Invalid Headers: ");
        // Build the error message then ...
        _error = sb.ToString();
        Logger.LogError(exc, "Invalid Headers");
    }
    catch (ValidationException exc)
    {
        _error = $"File validation error: {exc.Message}";
        Logger.LogError(exc, "File validation failed");
    }
    // Other specific exceptions and finally
    catch (Exception exc)
    {
        _error = exc.Message;
        Logger.LogError(exc,"Unexpected  error");
    }
    finally
    {
        _loading = false;

    }
}

Make your component accept a System.Drawing.Color parameter.

ComponentName.razor:

@using System.Drawing

<div style="background-color: @HexColor; height: 50px; width: 50px;"></div>

@code {
    [Parameter]
    public Color Color { get; set; }

    private string HexColor => ColorTranslator.ToHtml(Color);
}

Usage:

@page "/"
@using System.Drawing

<h1>Hello, world!</h1>

Welcome to your new app.

<ComponentName Color="Color.Red" />
<ComponentName Color="Color.Pink" />
<ComponentName Color="_componentColor" />

@code {
    private Color _componentColor = Color.Blue;
}

Demo: https://blazorfiddle.com/s/8eewuamw

Alternatively:

You can use the Color.FromName method which accepts a string parameter and returns a System.Drawing.Color. e.g.

@using System.Drawing

<ComponentName Color="Color.FromName(_componentColorName)" />

@code {
    private string _componentColorName = "Blue";
}
转载请注明原文地址:http://anycun.com/QandA/1744907226a89309.html