Search code examples
dotvvm

DotVVM Change CssStyle property from a Panel component in runtime doesn't work


I'm trying to change a CssStyle property, 'background-color', from a Panel component programmatically through a Button click Command, but nothing happen. If I set the property on ViewModel Load() method, works. After page loads don't.

DefaultViewModel class scope:

private Panel p = new Panel();

DefaultViewModel, Load() method:

base.Context.View.Children.Add(p);
p.CssStyles.Add("height", "400px");
p.CssStyles.Add("width", "400px");
p.CssStyles.Add("background-color", "#c0c0c0");

Button click Command:

p.CssStyles.Remove("background-color");
p.CssStyles.Add("background-color", "#000fff");

There's something I forget?

My dotVVM version is 2.2.155.0 Visual Studio 2019 .NET Framework 4.7.2

Thank you.


Solution

  • DotVVM does not work this way, controls don't have any state and thus manipulating them in commands does not make much sense. Controls in DotVVM are just thin wrappers around the HTML that is sent to the client on the first request. Since no HTML is generated on commands, modifications of the controls don't propagate to the browser (except when you use Postback.Update property on the control)

    You want to store the state in your view model and then data bind it to the control. I'm not sure what exactly you want to do so let's suppose you want to highlight a div in some cases. The markup (in dothtml file) could look like this:

    <div Style-background-color="{value: IsHighlighted ? "#000fff" : "#c0c0c0"}">
        ...
    </div>
    

    or like this if you'd prefer to use a css class

    <div Class-highlight="{value: IsHighlighted}">
        ...
    </div>
    

    The corresponding view model would just contain the property IsHighlighted and your command would just assign true to it:

    
    public bool IsHighlighted { get; set; }
    
    public void DoSomething() {
        this.IsHighlighted = true;
    }