4 .net c# data-binding wpf datetime
我正在尝试构建一个 gui,其中包括编辑对象的 DateTime 值。DateTime 属性绑定到一个 DataPicker 和一个普通的时间文本框。当我更改时间文本框中的值时,日期时间属性中写入的值是今天输入的时间,而不是仅更新时间,保留原始日期。
如何实现仅更改日期时间时间而不更改日期的时间文本框?
当前绑定:
<TextBlock>Time</TextBlock>
<TextBox Template="{StaticResource RoundedTextBoxTemplate}">
<Binding Path="Delivery.Date" StringFormat="HH:mm">
<Binding.ValidationRules>
<v:IsValidTimeRule />
</Binding.ValidationRules>
</Binding>
</TextBox>
Run Code Online (Sandbox Code Playgroud)
我能想到的唯一方法是拥有一个 DateTime 属性,只允许设置器更改时间。
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>
Run Code Online (Sandbox Code Playgroud)
C# 背后的代码:
public partial class Page : UserControl
{
private TestClass m_testClass = new TestClass();
public Page()
{
InitializeComponent();
myTextBox.DataContext = m_testClass;
}
}
Run Code Online (Sandbox Code Playgroud)
使用属性 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) => {};
}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16871 次 |
| 最近记录: |