我有一个文本框,它绑定到实体对象上的文本属性。 在某些情况下,我想重新格式化用户输入的文本-例如,如果用户输入“2/4”(一种分数),我想将其更改为“1/2”。
通过Text属性的“set部分”,我可以更改实体对象上的值,但是文本框仍然显示“2/4”,并没有更新为新的值。
我有一个文本框,它绑定到实体对象上的文本属性。 在某些情况下,我想重新格式化用户输入的文本-例如,如果用户输入“2/4”(一种分数),我想将其更改为“1/2”。
通过Text属性的“set部分”,我可以更改实体对象上的值,但是文本框仍然显示“2/4”,并没有更新为新的值。
textBox.GetBindingExpression(TextBox.TextProperty).UpdateTarget();
啊哈!将绑定更改为IsAsync=true:
<TextBox x:Name="textBox" Text="{Binding Path=TestData, IsAsync=true}"/>
似乎会改变行为,使其在setter触发PropertyChanged事件时注意它。
你是否实现了INotifyPropertyChanged并调用了它?
private string _fraction;
public string Fraction
{
get { return _fraction; }
set
{
_fraction = ReduceFraction(value);
NotifyPropertyChanged("Fraction");
}
}
private string ReduceFraction(string value)
{
string result = "1/2";
// Insert reduce fraction logic here
return result;
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
IsAsync=true
对我来说起作用了,但由于现在我的属性被非 GUI 线程使用,导致出现了一些跨线程异常。如果您添加了IsAsync=true
,请确保考虑到线程问题。或者,可以使用这个解决方案代替:http://www.lhotka.net/weblog/DataBindingIssueInWPFWithSolution.aspx。 - Joe DaleyIsAsync=…
或Converter=…
:] - mousio