如何在不丢失silverlight绑定的情况下更改TextBox.Text

时间:2014-04-10 11:36:08

标签: c# silverlight xaml input binding

我有一个绑定到类属性

的文本框
 <TextBox x:Name="TradeTextBox" 
    Text="{Binding Path=Entier,
                   Mode=TwoWay,
                   NotifyOnValidationError=True,
                   ValidatesOnExceptions=True,
                   UpdateSourceTrigger=Explicit}"/>

这是我的财产:

private string _entier;
public string Entier
        {
            get { return _entier; }
            set
            {
                if (!Regex.IsMatch(Entier.Trim(), NumberPattern, RegexOptions.IgnoreCase))
                    throw new ArgumentException("can only have numbers not characters");
                _entier = value;
                OnPropertyChanged("Entier");
            }
        }

如您所见,我正在使用异常验证并通知属性已更改 现在,我的问题是:当我尝试从主类构造函数初始化textBox.Text时,文本显示为空...

我试图这样做,但有些方法不起作用:

 public MyClass()
    {
        TradeTextBox.Text = "30";
        TradeTextBox.GetBindingExpression(TextBox.TextProperty).UpdateSource();
    }
你能帮帮我吗?请弄清楚为什么在运行应用程序时textBox.text未设置为“30”?

2 个答案:

答案 0 :(得分:2)

我的意思是看起来好像你将文字设置为30然后从你的来源获得价值,这不是30。

为什么不将源值设为30?

编辑 - 根据源文件的位置,它将只是

sourcevalue = textbox.text

如果你告诉我更多关于你的来源的话,我可以提供更好的答案。

答案 1 :(得分:0)

您可以通过几种方法设置默认值:

以xaml(-binding)声明:

<TextBox x:Name="TradeTextBox" 
    Text="{Binding Path=Entier,
                   TargetNullValue='30',
                   Mode=TwoWay,
                   NotifyOnValidationError=True,
                   ValidatesOnExceptions=True,
                   UpdateSourceTrigger=Explicit}"/>

作为Viewmodel属性的默认值:

private string _entier = "30";
public string Entier
    {
        get { return _entier; }
        set
        {
            if (!Regex.IsMatch(Entier.Trim(), NumberPattern, RegexOptions.IgnoreCase))
                throw new ArgumentException("can only have numbers not characters");
            _entier = value;
            OnPropertyChanged("Entier");
        }
    }

最后......使用一些代码(不会触及现有的绑定,但我不确定这是否真的有必要):

public MyClass()
{
    InitializeComponent();
}
public void CheckBoxChecked()
{
    SetBinding(TagProperty, new Binding("Text"){Source=TradeTextBox, Mode=TwoWay});
    Tag="30";
}
相关问题