所以我设置了一个简单的文本框
<Window x:Class="MyProject.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{Binding}" xmlns:Local="clr-namespace:MyProject">
<TextBox Name="txb_userActivity" IsEnabled="False" IsReadOnly="True">
<TextBox.Text>
<Binding Path="lastUserActivity">
</Binding>
</TextBox.Text>
</TextBox>
</Window>
我正在尝试设置媒体资源:
namespace MyProject{
public partial class MainWindow : Window{
private DateTime _lastUserActivity = DateTime.Now;
public DateTime lastUserActivity{
set {
_lastUserActivity = value;
}
get {
return _lastUserActivity;
}
}
}
}
这样,当属性更改时,文本框将更新其值:
lastUserActivity = DateTime.Now;
我的代码不起作用,该怎么办?
您的视图需要通知它必须进行更新。
您必须使用DependencyProperty
或实现INotifyPropertyChanged
,然后您的设置器应该看起来像
private DateTime _lastUserActivity = DateTime.Now;
public DateTime LastUserActivity {
set {
_lastUserActivity = value;
}
get {
return _lastUserActivity;
OnPropertyChanged("LastUserActivity")
}
}
此外,您应该使用ViewModel,并且不要在Window的代码背后使用此Property。如果要使绑定工作,则必须DataContext
为此ViewModel设置a 。当您将其保留在后面的代码中时,必须将Window设置为DataContext
。
编辑:对于DependencyObject
s,您应该这样使用DependencyProperty
:
// Dependency Property
public static readonly DependencyProperty LastUserActivityProperty =
DependencyProperty.Register( "LastUserActivity", typeof(DateTime),
typeof(MainWindow), new FrameworkPropertyMetadata(DateTime.Now));
// .NET Property wrapper
public DateTime LastUserActivity
{
get { return (DateTime)GetValue(LastUserActivityProperty); }
set { SetValue(LastUserActivityProperty, value); }
}
但同样:如果您希望使用绑定,则应该熟悉MVVM原理,并使用ViewModel而不是后台代码。像这样的东西:http : //www.codeproject.com/Articles/165368/WPF-MVVM-Quick-Start-Tutorial
edit2:您的DataContext错误。
<Window x:Class="MyProject.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{Binding RelativeSource={RelativeSource Self}}" xmlns:Local="clr-namespace:MyProject">
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句