【发布时间】:2011-09-21 19:51:02
【问题描述】:
首先,如果这听起来很愚蠢,我深表歉意,但我对 WPF 很陌生。我正在做一个计时器,我想更改标签以显示剩余时间。我尝试直接更改内容并通过数据绑定到属性。当我做前者时,程序就会崩溃;至于后者,我真的不明白它是如何工作的,我环顾四周,我所能做的就是从网络上的代码 sn-ps 中获取一些提示,但它不起作用,因为我不知道是什么我在做,我也不知道哪里出错了。
代码:我在 MainWindow 类上放了很多东西,这不是很好的代码,但对于我的目的来说已经足够了。当我尝试直接更改内容时,我通过设置由我的计时器类调用的委托来做到这一点,调用时会这样做:
private void updateTimerLabel()
{
lblTimer.Content = TimeToGo;
}
其中 TimeToGo 是以下属性:
public String TimeToGo
{
get { return task.TimeToGo.Hours + ":" +
task.TimeToGo.Minutes + ":" + task.TimeToGo.Seconds; }
}
至于绑定尝试,我设置了以下依赖属性:
public static readonly DependencyProperty TimeToGoProperty = DependencyProperty.Register(
"TimeToGo", typeof(String), typeof(MainWindow));
并在 XAML 文件中执行此操作:
<Window x:Class="ToDoTimer.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="ToDoTimer" Height="210" Width="348"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid Width="326" Height="180">
<Label Content="{Binding TimeToGoProperty}" Height="63" HorizontalAlignment="Left" Margin="12,12,0,104" Name="lblTimer" VerticalAlignment="Center" FontSize="40" Width="218" FontFamily="Courier New" VerticalContentAlignment="Center" />
</Grid>
</Window>
【问题讨论】:
标签: c# wpf xaml data-binding