【问题标题】:How to set XAML Element to default to current year?如何将 XAML 元素设置为默认为当年?
【发布时间】:2020-01-29 22:35:05
【问题描述】:

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

<tools:NumberTextBox x:Name="txtYear" FocusManager.FocusedElement="{Binding ElementName=txtYear}" Width="100" Text="{Binding Path=HistoryYear, UpdateSourceTrigger=PropertyChanged}"/>

【问题讨论】:

    标签: c# .net xaml mvvm


    【解决方案1】:

    您可以使用以下代码

    <Window.Resources>
            <sys:String x:Key="YearStyle">yyyy</sys:String>
        </Window.Resources>
    
    <TextBlock Text="{Binding 
               Source={x:Static sys:DateTime.Now},StringFormat={StaticResource YearStyle}}"/>
    

    其中“sys:”定义为 System(如下所示)命名空间。

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

    【讨论】:

      【解决方案2】:

      可以像这样在 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 或代码隐藏取决于您应用的架构。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多