如何将XAML元素设置为当前年份的默认值?

问题描述 投票:1回答:2

我在底部具有以下XAML代码,它与图片中突出显示的数字文本框对应:我的目标是当选中“当前”单选按钮时,将当前年份作为此数字文本框中的默认数字。当前单选按钮“当前已选择”时,当前默认为0。可以通过视图中的XAML完成此操作,还是会在视图模型中进行更改?

enter image description here

enter image description here

<tools:NumberTextBox x:Name="txtYear" FocusManager.FocusedElement="{Binding ElementName=txtYear}" Width="100" Text="{Binding Path=HistoryYear, UpdateSourceTrigger=PropertyChanged}"/>
c# .net mvvm
2个回答
0
投票
可以像这样静态地在XAML中定义当前年份

<Window.Resources> <s:DateTime x:Key="CurrentYear">2020</s:DateTime> </Window.Resources> 其中“ s:”定义为系统(如下所示),使您可以访问系统名称空间中的对象。

xmlns:s="clr-namespace:System;assembly=mscorlib"

HOWEVER:您

不应这样做有两个原因。主要的原因是,据我所知,您无法使用Window.Resources中的DateTime.Now之类的东西来动态获取当年,因为在上面的示例中,存储在“ 2020”位置的值是一个字符串。这将需要每年手动更新,等等。应该要做的是,将TextBox的Text属性绑定到ViewModel中的属性,或者,如果您尚未在此项目中使用视图模型,请在代码隐藏中进行设置。可以通过在这样的视图模型中创建可绑定属性来实现]

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或代码中完成-取决于应用的架构。

您可以使用以下代码,这将显示当前日期时间,使用string.format获取当前年份

<TextBox Text="{Binding Source={x:Static sys:DateTime.Now}}" />
其中“ sys:”定义为系统(如下所示)名称空间。

xmlns:sys =“ clr-namespace:System; assembly = mscorlib”


0
投票
© www.soinside.com 2019 - 2024. All rights reserved.