【问题标题】:How do I change TextBox.Text without losing the binding in silverlight如何更改 TextBox.Text 而不会丢失 silverlight 中的绑定
【发布时间】:2014-05-24 02:15:05
【问题描述】:

我有一个绑定到类属性的文本框

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

【问题讨论】:

  • 你应该只更新被绑定的东西,而不是文本框。绑定的全部意义在于更新文本框应该更新的基础值。

标签: c# silverlight xaml input binding


【解决方案1】:

我的意思是您将文本设置为 30,然后从您的源获取值,而不是 30。

为什么不将源值设为 30?

编辑-取决于您的源文件在哪里

sourcevalue = textbox.text

如果您告诉我更多有关您的来源的信息,我可以提供更好的答案。

【讨论】:

  • 感谢您的回答,但是如果我想创建一个条件:例如,如果 checkBox1 是 Chekecd,我想要 textbox.tex="30" 否则 textBox.Text="10"。 ..有没有办法以这种方式更新文本框源?
【解决方案2】:

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

在 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";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-08
    • 2018-11-14
    • 2011-04-27
    • 2015-04-20
    • 2017-12-07
    • 2010-11-10
    • 1970-01-01
    相关资源
    最近更新 更多