Rub*_*ben 5 c# wpf binding timespan mvvm
我希望能够在文本框中设置分钟和秒.我现在只是将我的文本框绑定到属性,这是一个TimeSpan属性.所以现在在我的文本框中,默认为:00:00:00.
这很好,但我希望能够有00:00.这样就可以消除时间.
我该怎么做呢?我在网上搜索但找不到任何好的解决方案
谢谢!
这是我的约束力:
public TimeSpan MaxTime
{
get
{
if (this.Examination.MaxTime == 0)
return TimeSpan.Zero;
else
return maxTime;
}
set
{
maxTime = value;
OnPropertyChanged("MaxTime");
TimeSpan x;
this.Examination.MaxTime = int.Parse(maxTime.TotalSeconds.ToString());
}
}
Run Code Online (Sandbox Code Playgroud)
<TextBox Height="23" HorizontalAlignment="Left" Margin="215,84,0,0" Text="{Binding Path=MaxTime,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" VerticalAlignment="Top" Width="50" />
Run Code Online (Sandbox Code Playgroud)
Dre*_*kes 10
如果你只想要单向绑定,那么你可以使用StringFormat
:
<TextBlock Text="{Binding MaxTime, StringFormat={}{0:hh\:mm}}" />
Run Code Online (Sandbox Code Playgroud)
如果你想要双向绑定,那么我会选择自定义值转换器.
[ValueConversion(typeof(TimeSpan), typeof(String))]
public class HoursMinutesTimeSpanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
Globalization.CultureInfo culture)
{
// TODO something like:
return ((TimeSpan)value).ToString("hh\:mm");
}
public object ConvertBack(object value, Type targetType, object parameter,
Globalization.CultureInfo culture)
{
// TODO something like:
return TimeSpan.ParseExact(value, "hh:\mm", CultureInfo.CurrentCulture);
}
}
Run Code Online (Sandbox Code Playgroud)