如果你只在顯示和檢索Dcitionary
的值,則可以使用下面的選項
視圖模型
class ExpenseViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propName)
{
var pc = PropertyChanged;
if (pc != null)
{
pc(this, new PropertyChangedEventArgs(propName));
}
}
private void Populate()
{
_mySource.Add("Test 1", DateTime.Now);
_mySource.Add("Test 2", DateTime.Now.AddDays(1));
_mySource.Add("Test 3", DateTime.Now.AddDays(2));
_mySource.Add("Test 4", DateTime.Now.AddDays(3));
NotifyPropertyChanged("MySource");
}
private Dictionary<string, DateTime> _mySource;
public Dictionary<string, DateTime> MySource
{
get { return _mySource; }
}
public ExpenseViewModel()
{
_mySource = new Dictionary<string, DateTime>();
Populate();
}
public DateTime SelectedDate
{
get;
set;
}
}
感興趣View.xaml
<StackPanel HorizontalAlignment="Left">
<StackPanel.Resources>
<local:Converters x:Key="Converter"/>
</StackPanel.Resources>
<ComboBox x:Name="cmbBox" Width="200" Margin="10,0,20,0" ItemsSource="{Binding MySource, Converter={StaticResource Converter}}"
SelectedItem="{Binding SelectedDate, Mode=TwoWay}" Height="20">
</ComboBox>
</StackPanel>
,當地是該項目的含轉換器 轉換
public class Converters : IValueConverter
{
private static readonly PropertyInfo InheritanceContextProp = typeof(DependencyObject).GetProperty("InheritanceContext", BindingFlags.NonPublic | BindingFlags.Instance);
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var dic = value as Dictionary<string, DateTime>;
return dic.Values;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
鑑於後面的代碼我剛纔定義在DataContext
Dictionary的元素是KeyValuePair,所以你可以通過該結構的屬性Value來獲得DateTime部分。無論如何,使用Dictionary作爲數據源並不是個好主意。 –
Spawn