[英]WPF multibound textblock not updating
我想創建一個程序,該程序計算重復執行一定次數所需的時間。 在本例中,我已經將其縮小了很多。
因此,我有一些文本框綁定到類中的屬性:
Count: <TextBox x:Name="txtCount" Text="{Binding Count, Mode=TwoWay}" Width="50"/>
Days: <TextBox x:Name="txtDays" Text="{Binding Days, Mode=TwoWay}" Width="50"/>
和一個像這樣的多邊界文本塊:
<TextBlock x:Name="tbkTotal">
<TextBlock.Text>
<MultiBinding StringFormat="Days: {0}, Count: {1}">
<Binding Path="Days" /> /* This isn't updating */
<Binding Path="Count" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
我的DataContext在Window1.xaml.cs文件中設置。
public Window1()
{
InitializeComponent();
Sample sample = new Sample();
this.DataContext = sample;
}
我可以使用Count屬性很好地更新多邊界文本塊,但是即使Days輸入准確反映了更改,Days屬性也始終顯示0。 我認為這是因為Days的訪問器有所不同-即Set方法。 此類位於其他文件中。
public class Sample : INotifyPropertyChanged
{
private int _count;
private TimeSpan _span;
public int Count
{
get { return _count; }
set
{
_count = value;
NotifyPropertyChanged("Count"); /* Doesn't seem to be needed, actually */
}
}
public TimeSpan Span { get { return _span; } }
/* The idea is to provide a property for Days, Hours, Minutes, etc. as conveniences to the inputter */
public double Days
{
get { return _span.Days; }
set
{
TimeSpan ts = new TimeSpan();
double val = value > 0 ? value : 0;
ts = TimeSpan.FromDays(val);
_span.Add(ts); /* !! This turned out to be the problem, lol - see SixLetterVariables' answer below. */
NotifyPropertyChanged("Span"); /* Here I can only get it to work if I notify that Span has changed - doesn't seem to be aware that the value behind Days has changed. */
}
}
private void NotifyPropertyChanged(string property)
{
if (null != this.PropertyChanged)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
public Sample()
{
_count = 0;
_span = new TimeSpan();
}
public event PropertyChangedEventHandler PropertyChanged;
}
首先, TimeSpan
是一個不可變的結構,因此您需要存儲任何操作的結果,否則它實際上是無操作的。 此外,您還需要針對更改的Span
和Days
調用OnPropertyChanged
:
public double Days
{
get { return _span.Days; }
set
{
double val = value > 0 ? value : 0;
// TimeSpan is an immutable struct, must store the result of any
// operations on it
_span = TimeSpan.FromDays(val);
this.OnPropertyChanged("Days");
this.OnPropertyChanged("Span");
}
}
// This is preferred way for handling property changes
private event PropertyChangedEventHandler propertyChanged;
public event PropertyChangedEventHandler PropertyChanged
{
add { this.propertyChanged += value; }
remove { this.propertyChanged -= value; }
}
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = this.propertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.