我在數據庫中的值是總月數。在我的WPF UI中,我需要顯示並更新此值作爲年數和月數。我很努力讓綁定在這個控件中工作,這樣我可以使用兩個單獨的文本框(年和月)查看和更新總月份的這一個值。WPF用戶控件從一個總月數值中顯示年份和月份
任何人都可以幫忙嗎?
我在數據庫中的值是總月數。在我的WPF UI中,我需要顯示並更新此值作爲年數和月數。我很努力讓綁定在這個控件中工作,這樣我可以使用兩個單獨的文本框(年和月)查看和更新總月份的這一個值。WPF用戶控件從一個總月數值中顯示年份和月份
任何人都可以幫忙嗎?
在作爲綁定源的類(例如ViewModel)中,您可以添加兩個屬性,以便在需要時計算兩個值。例如:
private const int MonthsInAYear = 12; // pedagogic purposes only :)
// This field contains the updated database value
private int _timeInMonths;
public int TimeYears
{
get { return _timeInMonths/MonthsInAYear; }
}
public int TimeMonths
{
get { return _timeInMonths % MonthsInAYear; }
}
如果您希望這些值進行自動更新,使這個類實現INotifyPropertyChanged
接口,提高PropertyChanged
事件這兩個屬性每當_timeInMonths
變化值。
我猜你應該使用一個轉換器,你一個月值轉換爲相應的年份和月份values.Or您可以在您的視圖模型本身
樣品
public class MonthConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if(((string)parameter)=="Year")
{
return (int)value/12;
}
if (((string)parameter) == "Month")
{
return (int)value % 12;
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
,並在您的XAML
做<StackPanel Orientation="Horizontal">
<TextBlock Height="23" Text="{Binding TotalMonths,Converter={StaticResource MonthConverter},ConverterParameter='Year',StringFormat={}{0}Years}"/>
<TextBlock Height="23" Text="{Binding TotalMonths,Converter={StaticResource MonthConverter},ConverterParameter='Month',StringFormat={}{0}Months}"/>
</StackPanel>
你需要雙向綁定,對吧? – 2010-12-14 18:35:01