WPF绑定到类并显示验证错误

时间:2019-04-06 22:31:06

标签: wpf data-binding wpf-controls

我正在尝试在WPF页面中设置绑定。我正在引用这篇文章: https://docs.microsoft.com/en-us/dotnet/framework/wpf/data/how-to-create-a-binding-in-code

我正在动态创建控件,因此需要以编程方式设置所有绑定和验证。我想触发PropertyChanged事件并调用将对表单上的不同属性进行验证的类。如果验证失败,我想使用设计器页面中的验证模板在表单上显示错误。我在做什么错了?

我的用户类别:

public class User : INotifyPropertyChanged
{
    private string _userName;

    public string UserName
    {
        get { return _userName; }
        //set
        //{
        //    _firstName = value;
        //    if (String.IsNullOrEmpty(value))
        //    {
        //        throw new Exception("Customer name is mandatory.");
        //    }
        //}
        set
        {
            _firstName = value;
            OnPropertyChanged("UserName");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string info)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(info));
    }
}

我后面的代码可以动态创建控件:

 UserName= new TextPanel(); //TextStackPanel is a user control
 //make a new source
            ViewModelUser bindingObject = new ViewModelUser();
            //Binding myBinding = new Binding("MyDataProperty");
            Binding myBinding = new Binding("UserName");
            myBinding.Source = bindingObject;
            BindingOperations.SetBinding(UserName, TextBox.TextProperty, myBinding);
            bindingObject.PropertyChanged += OnPropertyChangedMine;

我的xaml设计器页面具有以下内容:

<Page.Resources>

    <ControlTemplate x:Key="ValidationTemplate">
        <DockPanel>
            <TextBlock Foreground="Red" FontSize="20">!</TextBlock>
            <AdornedElementPlaceholder/>
        </DockPanel>
    </ControlTemplate>

    <Style x:Key="TextBoxInError" TargetType="{x:Type TextBox}">
        <Style.Triggers>
            <Trigger Property="Validation.HasError" Value="true">
                <Setter Property="ToolTip"
          Value="{Binding RelativeSource={x:Static RelativeSource.Self},
                          Path=(Validation.Errors)[0].ErrorContent}"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</Page.Resources>

1 个答案:

答案 0 :(得分:0)

如果通过抛出异常进行验证,则应将ValidatesOnExceptions的{​​{1}}属性设置为Binding

您还需要将true控件的Style属性设置为TextBox,并且您可能还希望将Style设置为UpdateSourceTrigger让设置者在每次击键时都被调用:

PropertyChanged

请注意,您不能将TextBox textBox = new TextBox() { Style = FindResource("TextBoxInError") as Style }; User bindingObject = new User(); Binding myBinding = new Binding("UserName") { ValidatesOnExceptions = true, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged }; myBinding.Source = bindingObject; BindingOperations.SetBinding(textBox, TextBox.TextProperty, myBinding); Style的{​​{1}}应用于TargetType