[英]Textbox.Text input not binding to Property
我有一個創建的對象,並希望通過模式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;
}
}
它可以正確驗證,但每次檢查屬性是否更新時,它都不會。 我真的需要幫助,任何幫助將不勝感激。
你有2個HoursWorked類的實例。
一個是在參考資料中通過這個標簽<my:HoursWorked x:Key="hwViewSource" />
創建的,但是你在窗口中創建了一個newLog = new HoursWorked(); 並將其設置為adminTimeTxtBox的DataContext ...因此您綁定到的(資源一)與您正在更新的那個(Window內的一個)不同。
您可以將Binding更改為
<Binding Source="{Binding}"
....
然后不需要在Resource中定義的那個。
TextBox.Text
屬性的類型為string,您的Hours
屬性為double。
您必須創建ValueConverter
或輔助屬性以將字符串解析為double,反之亦然。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.