我有一個對象被創建,並希望通過該模式綁定到該對象的屬性OneWayToSource明確。然而,這種綁定根本不起作用。當程序初始化時,它在文本框右側也有一個紅色邊框,當我點擊按鈕時,只希望輸入有效。我最後一次溝通是將源頭嵌入元素本身,但沒有這樣的運氣。以下是我有:Textbox.Text輸入沒有約束力物業
<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;
}
}
它驗證正確,但每次我檢查是否屬性更新,它不會。我真的需要幫助,任何幫助將不勝感激。
哦,沒關係,工作。我只是想知道,如果我只是使用了資源之一,是否意味着我不必創建一個新的HoursWorked()實例?我將如何能夠將這個特定的對象添加到集合中?我將如何參考它? – Erika 2012-07-30 22:42:23
如果你想引用在你的資源中創建的實例...那麼你可以在你的代碼隱藏中使用它的關鍵字來做FindResource ...然後你會引用同一個實例....但是你'堅持StaticResource綁定。 – 2012-07-30 22:45:05