您可以创建一个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;
}
}
您将您的 ComboBox 绑定到这些集合中,使用CurrentDateExample
您的DataTemplate
或作为 ComboBox 的DisplayMemberPath
. 您可以直接将这些对象与您的日期格式选择器类一起使用并DatePicker
绑定到FormatCode
所选DateFormatChoice
对象的属性,或者您可以将ValueMemberPath
原始 ComboBox 上的属性设置为该属性FormatCode
并在 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" ) );
}
}
然后我为窗口制作了简单的 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
type的依赖属性,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>