我正在使用下面的内容在TimeBone Info中填充组合框:
MainWindow.xaml.cs
private void Window_Loaded(object sender, RoutedEventArgs e)
{
ReadOnlyCollection<TimeZoneInfo> TimeZones = TimeZoneInfo.GetSystemTimeZones();
this.DataContext = TimeZones;
cmb_TZ.SelectedIndex = 1;
}
The below is from the XAML:
<ComboBox x:Name="cmb_TZ" ItemsSource="{Binding}" Grid.Row="0" Grid.Column="2" Height="28.5" Margin="10,65.375,30.945,0" VerticalAlignment="Top" d:LayoutOverrides="LeftMargin, RightMargin, TopMargin, BottomMargin" SelectionChanged="ComboBox_Selection"/>
通过使用以下代码,我还可以在文本框中显示相应的值:
private void ComboBox_Selection(object Sender, SelectionChangedEventArgs e)
{
var cmbBox = Sender as ComboBox;
DateTime currTime = DateTime.UtcNow;
TimeZoneInfo tst = (TimeZoneInfo)cmbBox.SelectedItem;
txt_Time.Text = TimeZoneInfo.ConvertTime(currTime, TimeZoneInfo.Utc, tst).ToString("HH:mm:ss dd MMM yy");
}
txt_Time是我的文本框.它的XAML代码是:
<TextBox x:Name="txt_Time" Grid.Row="0" Grid.Column="1" Height="28.5" Margin="26.148,65.375,28.13,0" TextWrapping="Wrap" VerticalAlignment="Top" d:LayoutOverrides="LeftMargin, RightMargin, TopMargin, BottomMargin"/>
My question is :
有没有一种方法可以使用数据绑定来实现?
我可以使用上面显示的简单方法来做到这一点.但是我想知道是否可以通过数据绑定完成此计算?
我是C#/ WPF的新手,我尝试创建一个简单的类以及一个使用INotifyPropertyChanged的类,并在MainWindow构造函数中对其进行引用,但是我什至无法填充组合框.
我真的很想了解和使用C#的数据绑定魔术.
解决方法:
在标准MVVM方法中,您将创建一个具有两个属性的视图模型类,一个为所有TimeZoneInfos的只读集合,一个为当前选择的TimeZone的只读集合.
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public ReadOnlyCollection<TimeZoneInfo> TimeZones { get; }
= TimeZoneInfo.GetSystemTimeZones();
private TimeZoneInfo selectedTimeZone = TimeZoneInfo.Local;
public TimeZoneInfo SelectedTimeZone
{
get { return selectedTimeZone; }
set
{
selectedTimeZone = value;
PropertyChanged?.Invoke(this,
new PropertyChangedEventArgs("SelectedTimeZone"));
}
}
}
您可以将窗口的DataContext设置为视图模型的实例,并绑定ComboBox和TextBox属性,如此XAML所示:
<Window ...>
<Window.DataContext>
<local:ViewModel/>
</Window.DataContext>
<Window.Resources>
<local:TimeZoneConverter x:Key="TimeZoneConverter" />
</Window.Resources>
<StackPanel>
<ComboBox ItemsSource="{Binding TimeZones}"
SelectedItem="{Binding SelectedTimeZone}" />
<TextBox Text="{Binding SelectedTimeZone,
Converter={StaticResource TimeZoneConverter}}"/>
</StackPanel>
</Window>
绑定到文本属性使用的转换器是这样的:
public class TimeZoneConverter : IValueConverter
{
public object Convert(
object value, Type targetType, object parameter, CultureInfo culture)
{
return value == null ? string.Empty : TimeZoneInfo
.ConvertTime(DateTime.UtcNow, TimeZoneInfo.Utc, (TimeZoneInfo)value)
.ToString("HH:mm:ss dd MMM yy");
}
public object ConvertBack(
object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}