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

问题描述 投票:0回答:1

我正在尝试在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>
wpf data-binding wpf-controls
1个回答
0
投票

如果通过抛出异常进行验证,则应将ValidatesOnExceptionsBinding属性设置为true

您还需要将Style控件的TextBox属性设置为Style,并且您可能还需要将UpdateSourceTrigger设置为PropertyChanged,以便为每个击键调用setter:

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);

请注意,您不能将带有StyleTargetTypeTextBox应用于UserControl

© www.soinside.com 2019 - 2024. All rights reserved.