用户选择的东西在组合框,其他的东西是送给的依赖性
-
21-09-2019 - |
题
在我的应用程序的用户可以选择如何在日期显示。大多数 标准datetime格式串 可选择的。我现在的问题是,用户平均不理解之间的差异"m"和"D"。 什么我想要做的就是 改变这一因此,如excel会,而不是表示的格式的字符串中,我将展示如何任意的日期就会看起来像使用该格式。
WPF组合框SelectedItem定一个依赖性的日期格式选择器cla,其他控制含有这个的日期选择器也结合。
例:
- 用户选择"月15",因此依赖关系的财产被设定为"m"。
- 通过代码后面,值的依赖关系的财产被设定为"D"类、组合框为更新,以显示"星期四月15日1970年"作为选定项目。
我试图使用转换器,但ConvertBack是不可能的因为我不能提取的格式串用来创建一个特定的日期。
解决方案
你可以创建一个类 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
或组合框的 DisplayMemberPath
.你可以使用这些物体直接用您的日期格式选择器类和 DatePicker
结合 FormatCode
酒店的选择 DateFormatChoice
对象,或者你可以设定 ValueMemberPath
酒店对原组合框到 FormatCode
财产和使用 SelectedValue
在该组合框for getting/setting是什么选择。不使用 ValueMember
可能会更容易一些。
这里有一个更全面的例子。它使用 DateFormatChoice
类以上。
第一,数据收集。
public class DateFormatChoices : List<DateFormatChoice> {
public DateFormatChoices() {
this.Add( new DateFormatChoice( "m" ) );
this.Add( new DateFormatChoice( "d" ) );
this.Add( new DateFormatChoice( "D" ) );
}
}
然后我做了简单视图模型的窗口:
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 ) );
}
}
我没有日期选择器控制,接受的标准字符串的格式编码,所以我做了一个很愚蠢的用户控件(与许多切角的)只是为了证明其收到的格式编码。我给了它的依赖性所谓 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>