我正在尝试构建一个包含编辑对象的 DateTime 值的图形用户界面。 DateTime 属性已绑定(bind)到 DataPicker 和时间的普通 TextBox。 当我更改 Time TextBox 中的值时,DateTime 属性中的值是 Today 和输入的时间,而不是仅仅更新时间,保留原始日期。
如何实现只更改 DateTime 时间而不更改日期的时间文本框?
当前绑定(bind):
<TextBlock>Time</TextBlock>
<TextBox Template="{StaticResource RoundedTextBoxTemplate}">
<Binding Path="Delivery.Date" StringFormat="HH:mm">
<Binding.ValidationRules>
<v:IsValidTimeRule />
</Binding.ValidationRules>
</Binding>
</TextBox>
最佳答案
我能想到的唯一方法是拥有一个 DateTime 属性,您只允许 setter 更改时间。
XAML:
<UserControl.Resources>
<mine:DateTimeConverter x:Key="MyDateTimeConverter" />
</UserControl.Resources>
<Grid x:Name="LayoutRoot">
<TextBox x:Name="myTextBox" Text="{Binding Path=TestDateTime, Converter={StaticResource MyDateTimeConverter}, Mode=TwoWay}" />
</Grid>
C# 代码隐藏:
public partial class Page : UserControl
{
private TestClass m_testClass = new TestClass();
public Page()
{
InitializeComponent();
myTextBox.DataContext = m_testClass;
}
}
使用属性 setter 限制的 C# TestClass:
public class TestClass : INotifyPropertyChanged
{
private DateTime m_testDateTime = DateTime.Now;
public DateTime TestDateTime
{
get { return m_testDateTime; }
set
{
m_testDateTime = m_testDateTime.Date.Add(value.TimeOfDay);
PropertyChanged(this, new PropertyChangedEventArgs("TestDateTime"));
}
}
public event PropertyChangedEventHandler PropertyChanged = (t, e) => {};
}
C# IValueConverter:
public class DateTimeConverter : IValueConverter
{
public object Convert(object value,
Type targetType,
object parameter,
CultureInfo culture)
{
DateTime date = (DateTime)value;
return date.ToString("HH:mm");
}
public object ConvertBack(object value,
Type targetType,
object parameter,
CultureInfo culture)
{
string strValue = value.ToString();
DateTime resultDateTime;
if (DateTime.TryParse(strValue, out resultDateTime))
{
return resultDateTime;
}
return value;
}
}
关于c# - 将 DateTime 绑定(bind)到日期和时间 EditFields,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/708843/