【问题标题】:WPF binding to class and display validation errorsWPF 绑定到类并显示验证错误
【发布时间】:2023-03-05 12:23:01
【问题描述】:

我正在尝试在 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>

【问题讨论】:

  • “我正在动态创建我的控件”——这就是你的问题所在。不要在代码中创建 UI 对象。使用模板。如果您真的想以错误的方式进行操作并希望 SO 社区提供帮助,请解决您的问题,以便包含一个好的 minimal reproducible example
  • 您没有在 Binding 对象上设置 ValidatesOnDataErrors 属性。阅读更多关于here.

标签: wpf data-binding wpf-controls


【解决方案1】:

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

您还需要将TextBox 控件的Style 属性设置为您的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);

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

【讨论】:

    猜你喜欢
    • 2019-06-17
    • 2014-08-08
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    • 1970-01-01
    • 2014-05-09
    • 1970-01-01
    • 2011-05-18
    相关资源
    最近更新 更多