我创建了一个对象,并希望通过 OneWayToSource 模式显式绑定到该对象的属性。但是,此绑定根本不起作用。当程序初始化时,它在文本框周围也有一个红色边框,当我只希望在单击按钮后验证输入时。我最后的努力是将源嵌入到元素本身,但没有这样的运气。这是我所拥有的:
<StackPanel.Resources>
<my:HoursWorked x:Key="hwViewSource" />
</StackPanel.Resources>
<TextBox Style="{StaticResource textBoundStyle}" Name="adminTimeTxtBox">
<Binding Source="{StaticResource hwViewSource}" Path="Hours" UpdateSourceTrigger="PropertyChanged" Mode="OneWayToSource">
<Binding.ValidationRules>
<my:NumberValidationRule ErrorMessage="Please enter a number in hours." />
</Binding.ValidationRules>
</Binding>
</TextBox>
HoursWorked 对象如下所示:
//I have omitted a lot of things so it's more readable
public class HoursWorked : INotifyPropertyChanged
{
private double hours;
public HoursWorked()
{
hours = 0;
}
public double Hours
{
get { return hours; }
set
{
if (Hours != value)
{
hours = value;
OnPropertyChanged("Hours");
}
}
}
#region Databinding
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(String info)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(info));
}
}
#endregion
}
初始化窗口后,这是我拥有的代码部分:
public partial class Blah : Window
{
private HoursWorked newLog;
public Blah()
{
InitializeComponent();
newLog = new HoursWorked();
adminTimeTxtBox.DataContext = newLog;
}
private void addAdBtn_Click(object sender, RoutedEventArgs e)
{
AddHours();
}
private void AddHours()
{
if (emp.UserType.Name == "Admin")
{
if(!ValidateElement.HasError(adminTimeTxtBox))
{
item.TimeLog.Add(newLog);
UpdateTotals();
adminTimeTxtBox.Clear();
}
}
}
}
最后 ValidateElement 看起来像这样:
public static class ValidateElement
{
public static bool HasError(DependencyObject node)
{
bool result = false;
if (node is TextBox)
{
TextBox item = node as TextBox;
BindingExpression be = item.GetBindingExpression(TextBox.TextProperty);
be.UpdateSource();
}
if (Validation.GetHasError(node))
{
// If the dependency object is invalid, and it can receive the focus,
// set the focus
if (node is IInputElement) Keyboard.Focus((IInputElement)node);
result = true;
}
return result;
}
}
它可以正确验证,但是每次我检查属性是否更新时,它都没有。我真的需要帮助,任何帮助将不胜感激。