简体   繁体   中英

Is it possible to reload XAML properties of a UserControl?

I have some frameworkElements inside XAML, and I define some properties like background, and cursor.

In code behind, I change these properties, and when an event triggers, I want to reload these initial properties defined in XAML. Is this possible or I need to redifine manually in code behind?

Thanks.

A control defined in XAML is essentially defining an instance . Once you have the instance , the object is just like every other object you deal with. Having access to the instance defined in XAML within your code behind is akin to creating a new object in the code behind and then adjusting its properties at run time.

When you want the property value to change; you don't revert your property changes, you simply change them to what you desire.

I would suggest looking into DataTriggers for making temporary changes based on some value. This will change the value of a property while a specific condition is true, and revert it to its original value when the condition is false.

For example, here's a style that will change the cursor to a Wait cursor while loading, and change the background to Red if it is invalid.

<Style TargetType="{x:Type local:MyUserControl}">
    <Setter Property="Cursor" Value="Arrow" />
    <Setter Property="Background" Value="White" />

    <Style.Triggers>
        <DataTrigger Binding="{Binding IsLoading}" Value="True">
            <Setter Property="Cursor" Value="Wait" />
        </DataTrigger>
        <DataTrigger Binding="{Binding IsValid}" Value="True">
            <Setter Property="Background" Value="Red" />
        </DataTrigger>
    </Style.Triggers>
</Style>

Of course, you'll have to define the IsLoading and IsValid properties behind your UserControl, and set them to true/false at the appropriate times in your code-behind.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM