大家好我需要在运行时动态生成属性,任何人都可以告诉我如何在运行时在WPF中生成属性。
<Style x:Key="EditableTextBox" TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}">
<Setter Property="Background" Value="#FFF8E48F" />
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<Border BorderBrush="Red" BorderThickness="2">
<AdornedElementPlaceholder />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="Background" Value="LightCoral"/>
<Setter Property="Background" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style
TextBox txt = new TextBox();
txt.Name = "txt1";
txt.Width = 200;
txt.Style = (Style)this.FindResource("EditableTextBox");
TextRequired txtreq = new TextRequired();
Binding txtbind = new Binding("MyText"); // name of the property
stp.Children.Add(txt);
txtbind.UpdateSourceTrigger = UpdateSourceTrigger.LostFocus;
txtbind.Mode = BindingMode.OneWayToSource;
txtbind.ValidationRules.Add(txtreq);
BindingOperations.SetBinding(txt, TextBox.TextProperty, txtbind);
public class TextRequired : ValidationRule {
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
if (value != null)
{
string input = value as string;
if (input.Length > 0)
return new ValidationResult(true, null);
}
return new ValidationResult(false, "Validation error. Field input required.");
}
}