如何动态生成WPF应用程序的属性

时间:2010-10-20 10:55:03

标签: c# wpf

大家好我需要在运行时动态生成属性,任何人都可以告诉我如何在运行时在WPF中生成属性。

在我的window.resource块

 <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 &gt; 0)
                    return new ValidationResult(true, null);
            }

            return new ValidationResult(false, "Validation error. Field input required.");
        }
    }

0 个答案:

没有答案