[英]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. 我在XAML中有一些frameworkElements,并且定义了一些属性,例如background和cursor。
In code behind, I change these properties, and when an event triggers, I want to reload these initial properties defined in XAML. 在后面的代码中,我更改了这些属性,并且在事件触发时,我想重新加载XAML中定义的这些初始属性。 Is this possible or I need to redifine manually in code behind? 这可能吗,或者我需要在后面的代码中手动重新定义?
Thanks. 谢谢。
A control defined in XAML is essentially defining an instance . XAML中定义的控件本质上是定义一个实例 。 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. 可以在后面的代码中访问XAML中定义的实例 ,类似于在后面的代码中创建一个新对象,然后在运行时调整其属性。
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. 我建议调查一下DataTriggers
,以便根据某些值进行临时更改。 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. 这将在特定条件为true时更改属性的值,并在条件为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. 当然,您必须在UserControl后面定义IsLoading
和IsValid
属性,并在后面的代码中的适当时间将它们设置为true / false。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.