您可以创建一个类DateFormatChoice,其中包含格式代码(例如“m”或“D”)的属性和以这种方式格式化的当前日期的属性。
public class DateFormatChoice {
public string FormatCode { get; private set; }
public string CurrentDateExample {
get { return DateTime.Now.ToString( FormatCode ) }
}
public DateFormatChoice( string standardcode ) {
FormatCode = standardcode;
}
}
您可以使用CurrentDateExample 在DataTemplate 中或作为ComboBox 的DisplayMemberPath 将您的ComboBox 绑定到这些集合。您可以将这些对象直接与日期格式选择器类一起使用,并将DatePicker 绑定到所选DateFormatChoice 对象的FormatCode 属性,或者您可以将原始ComboBox 上的ValueMemberPath 属性设置为@987654330 @ 属性并在 ComboBox 上使用 SelectedValue 来获取/设置所选择的内容。不使用ValueMember 可能会容易一些。
这里有一个更完整的例子。它使用上面的DateFormatChoice 类。
首先,数据收集。
public class DateFormatChoices : List<DateFormatChoice> {
public DateFormatChoices() {
this.Add( new DateFormatChoice( "m" ) );
this.Add( new DateFormatChoice( "d" ) );
this.Add( new DateFormatChoice( "D" ) );
}
}
然后我为 Window 制作了简单的 ViewModel:
public class ViewModel : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged = ( s, e ) => {
}; // the lambda ensures PropertyChanged is never null
public DateFormatChoices Choices {
get;
private set;
}
DateFormatChoice _chosen;
public DateFormatChoice Chosen {
get {
return _chosen;
}
set {
_chosen = value;
Notify( PropertyChanged, () => Chosen );
}
}
public DateTime CurrentDateTime {
get {
return DateTime.Now;
}
}
public ViewModel() {
Choices = new DateFormatChoices();
}
// expression used to avoid string literals
private void Notify<T>( PropertyChangedEventHandler handler, Expression<Func<T>> expression ) {
var memberexpression = expression.Body as MemberExpression;
handler( this, new PropertyChangedEventArgs( memberexpression.Member.Name ) );
}
}
我没有接受标准字符串格式代码的日期选择器控件,所以我制作了一个非常愚蠢的 UserControl(有许多切角),只是为了证明它接收格式代码。我给了它一个名为DateFormatProperty 类型为string 的依赖属性,并在UIPropertyMetadata 中指定了一个值更改回调。
<Grid>
<TextBlock Name="datedisplayer" />
</Grid>
回调:
private static void DateFormatChanged( DependencyObject obj, DependencyPropertyChangedEventArgs e ) {
var uc = obj as UserControl1;
string code;
if ( null != ( code = e.NewValue as string ) ) {
uc.datedisplayer.Text = DateTime.Now.ToString( code );
}
}
这就是我在窗口中将它们捆绑在一起的方式。
<StackPanel>
<StackPanel.DataContext>
<local:ViewModel />
</StackPanel.DataContext>
<ComboBox
ItemsSource="{Binding Choices}" DisplayMemberPath="CurrentDateExample"
SelectedItem="{Binding Chosen, Mode=TwoWay}"/>
<local:UserControl1
DateFormatProperty="{Binding Chosen.FormatCode}" />
</StackPanel>