您可以像这样在 XAML 中静态定义当前年份
<Window.Resources>
<s:DateTime x:Key="CurrentYear">2020</s:DateTime>
</Window.Resources>
其中“s:”被定义为 System(如下所示),让您可以访问 System 命名空间中的对象。
xmlns:s="clr-namespace:System;assembly=mscorlib"
但是:您不应该这样做有几个原因。主要的一个是,据我所知,您不能在 Window.Resources 中使用 DateTime.Now 之类的东西动态获取当前年份,因为在上面的示例中“2020”位置存储的值必须是一个字符串。这需要每年手动更新,等等。
您应该做的是将 TextBox 的 Text 属性绑定到 ViewModel 中的属性,或者如果您尚未在此项目中使用视图模型,则在代码隐藏中设置它.这可以通过在这样的视图模型中创建可绑定属性来实现
视图模型
public string CurrentYear { get; set; }
public MainViewModel()
{
// This could be set anywhere, but setting in the constructor like this works well for a default value.
CurrentYear = DateTime.Now.Year.ToString();
}
查看(xaml)
<!-- TwoWay Binding because the text can be updated by the user in the view, and it could be updated by the ViewModel -->
<TextBox Text="{Binding CurrentYear,
Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}" />
或者,您可以像这样在代码隐藏中执行此操作
View.xaml
<TextBox x:Name="currentYearTextBox" />
View.xaml.cs(代码隐藏)
public MainWindow()
{
InitializeComponent();
currentYearTextBox.Text = DateTime.Now.Year.ToString();
}
最后的想法:如果您只想在选择“当前”时显示当前年份,您只需根据 RadioButtons 的值等更新 CurrentYear 的值。这将在 ViewModel 或代码隐藏取决于您应用的架构。