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
inDataTemplate
または ComboBox の として使用して、ComboBox をこれらのコレクションにバインドしますDisplayMemberPath
。これらのオブジェクトを日付形式ピッカー クラスで直接使用し、選択したオブジェクトDatePicker
のプロパティにバインドするか、元の ComboBox のプロパティをプロパティに設定し、ComboBox で使用して、選択したものを取得/設定することができます。使わない方が少し楽かもしれません。FormatCode
DateFormatChoice
ValueMemberPath
FormatCode
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
タイプと呼ばれる依存関係プロパティ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>