【发布时间】: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