简体   繁体   English

Textbox.Text输入未绑定到Property

[英]Textbox.Text input not binding to Property

I have an object that is created, and want to bind to a property of that object through the mode OneWayToSource explicitly. 我有一个创建的对象,并希望通过模式OneWayToSource显式绑定到该对象的属性。 This binding however is not working at all. 然而,这种约束根本不起作用。 It also has a red border around the textbox right when the program is initialized, when I only want the input validated once I click the button. 当程序初始化时,它在文本框周围也有一个红色边框,当我单击按钮时我只想要输入验证。 My last ditch effor was embedding the source to the element itself, but no such luck. 我的最后一个问题是将源代码嵌入到元素本身,但没有这样的运气。 Here is what I have: 这是我有的:

<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>

The HoursWorked object looks like this: 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
}

once the window is initialized, this is the portion of code I have: 一旦窗口初始化,这是我的代码部分:

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();
        }
         }

    }
}

and finally ValidateElement looks like this: 最后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;

    }
}

It validates properly, but every time I check to see if the property updates, it doesn't. 它可以正确验证,但每次检查属性是否更新时,它都不会。 I really need help on this, any help would be greatly appreciated. 我真的需要帮助,任何帮助将不胜感激。

You've got 2 instances of the HoursWorked class. 你有2个HoursWorked类的实例。

One is created in Resources via this tag <my:HoursWorked x:Key="hwViewSource" /> but then you create one in your Window with newLog = new HoursWorked(); 一个是在参考资料中通过这个标签<my:HoursWorked x:Key="hwViewSource" />创建的,但是你在窗口中创建了一个newLog = new HoursWorked(); and set it into the DataContext of the adminTimeTxtBox...so the one your Binding to (the Resource one) isn't the same as the one you're updating (the one inside Window). 并将其设置为adminTimeTxtBox的DataContext ...因此您绑定到的(资源一)与您正在更新的那个(Window内的一个)不同。

You could change the Binding to 您可以将Binding更改为

<Binding Source="{Binding}" .... <Binding Source="{Binding}" ....

and then don't need the one defined in Resource. 然后不需要在Resource中定义的那个。

TextBox.Text property is of type string, your Hours property is double. TextBox.Text属性的类型为string,您的Hours属性为double。

You have to create a ValueConverter or an auxiliary property for parsing the string to double and vice versa. 您必须创建ValueConverter或辅助属性以将字符串解析为double,反之亦然。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM