[英]WPF Binding: disable TextBoxes + Validation and DataContext Issue
我的简单程序有两个窗口:
Boolean
值,然后... 所述文本框还以验证绑定为特征。 现在,我的验证任务可以正常工作,但是无法使与IsEnabled
TextBox属性的绑定IsEnabled
。
这是我的XAML的代码片段,其中包含一个TextBoxes(目前是我绑定的唯一一个):
<TextBox x:Name="tbSlave1" Validation.Error="ValidationError" IsEnabled="{Binding TextBoxEnabled}" Text="{Binding UpdateSourceTrigger=PropertyChanged, Path=SlavePoint1Name, ValidatesOnDataErrors=true, NotifyOnValidationError=true}"/>
这是我的第二个窗口类:
public partial class GeneratorWindow : Window, INotifyPropertyChanged
{
private readonly Validator validator = new Validator();
private int noOfErrorsOnScreen;
public GeneratorWindow()
{
this.InitializeComponent();
this.grid.DataContext = this.validator;
}
public int NumberOfPoints { private get; set; }
public int MainPDC { private get; set; }
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
private Boolean IsEnabled;
public Boolean TextBoxEnabled
{
get { return IsEnabled; }
set
{
IsEnabled = value;
NotifyPropertyChanged("TextBoxEnabled");
}
}
private void ValidationError(object sender, ValidationErrorEventArgs eventArgs)
{
if (eventArgs.Action == ValidationErrorEventAction.Added)
{
this.noOfErrorsOnScreen++;
}
else
{
this.noOfErrorsOnScreen--;
}
}
private void ValidationCanBeExecuted(object sender, CanExecuteRoutedEventArgs eventArgs)
{
eventArgs.CanExecute = this.noOfErrorsOnScreen == 0;
eventArgs.Handled = true;
}
private void ValidationExecuted(object sender, ExecutedRoutedEventArgs eventArgs)
{
// If the validation was successful, let's generate the files.
this.Close();
eventArgs.Handled = true;
}
}
现在,我回来的是我的窗口被禁用(无法选择任何TextBox),显然,这是:
System.Windows.Data错误:40:BindingExpression路径错误:在“对象”“ Validator”(HashCode = 14499481)“上找不到“ TextBoxEnabled”属性。 BindingExpression:Path = TextBoxEnabled; DataItem ='Validator'(HashCode = 14499481); 目标元素是'TextBox'(Name ='tbSlave1'); 目标属性为“ IsEnabled”(类型为“布尔”)
据我了解,罪魁祸首是我在类构造函数中管理DataContext
的方式。 我可能需要在验证行中添加一些内容或完全更改它,但我不知道如何操作。
我认为如果将DataContext
设置为GeneratorWindow
并相应地更新绑定,那应该没问题。 为此,您需要将Validator
更改为公共属性。
更改的验证器定义:
public Validator Validator { get; } = new Validator();
DataContext:
this.grid.DataContext = this;
更新的绑定:
<TextBox x:Name="tbSlave1"
Validation.Error="ValidationError"
IsEnabled="{Binding TextBoxEnabled}"
Text="{Binding UpdateSourceTrigger=PropertyChanged,
Path=Validator.SlavePoint1Name,
ValidatesOnDataErrors=true,
NotifyOnValidationError=true}"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.