【问题标题】:Bind current date time to TextBox and update the source property when I update it (WPF)将当前日期时间绑定到 TextBox 并在我更新它时更新源属性(WPF)
【发布时间】:2015-01-26 07:39:59
【问题描述】:

我想将当前日期和时间绑定到文本框,并且我想在更改值时更新源属性。我正在使用 MVVM 代码结构,我希望在 .xaml 文件中完成此任务

【问题讨论】:

  • 你能补充一些细节吗?更改值是什么意思?
  • 在我的实体类中,我有一个名为“SampleCurrentDate”的属性。我已将该属性绑定到 .xaml 文件中的 TextBox。当我在 UI 中更改日期时,我也想更改 SampleCurrentDate 属性值,

标签: wpf mvvm


【解决方案1】:

如果您有属性 Binding,请添加 Mode=TwoWay 以确保启用从 UI 到 ViewModel 的更新。

您可能需要添加一个带有 IValueConverter 实现的 Converter=... 属性,该实现从 DateTime 转换为 string,反之亦然。

如果您希望绑定在每次按键后更新,而不仅仅是失去焦点,您必须设置“绑定”的UpdateSourceTrigger-Property。

【讨论】:

  • 谢谢eFloh,我参考了这个链接link 和@BrokenGlass 回答我像这样创建了UserControl.Resource 和我的文本框是这样的 我的问题是,我的实体类中有一个名为“SampleCurrentDate”的属性,如何将该属性设置为 textBox 并绑定以影响我正在做的更改?
  • 您不能从一侧(StaticResource)绑定输入值并更新另一侧(EntityClass)。您必须将实体类中的 DateTime.Now 设置为默认值(例如在 ctor 中)并直接绑定到该属性。
【解决方案2】:

来自 WPF 的用户观察属性来实现相同的目标。

public class YourClass : INotifyPropertyChanged
{

  private string _mytime;
  public string MyTime
  {
      get { return _mytime; }
      set { _mytime= value; NotifyPropertyChanged("MyTime"); }
  }

  public event PropertyChangedEventHandler PropertyChanged;
  private void NotifyPropertyChanged(String propertyName)
  {
      PropertyChangedEventHandler handler = PropertyChanged;
      if (null != handler)
      {
          handler(this, new PropertyChangedEventArgs(propertyName));
      }
  }
}

现在您需要在 XAML 文件中附加 MyTime 属性,每当您在类文件中更新 MyTime 时,您都会在 UI 上看到更新后的值。

<TextBlock Text={Binding MyTime}/>

【讨论】:

  • 谢谢 Dnyanesh,我不清楚你的答案。能不能说的具体点。
  • 谢谢@Dnyanesh,但是如何在 .xaml 文件中设置当前日期时间。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-31
  • 1970-01-01
相关资源
最近更新 更多