我使用的是下面的填充我的組合框的時區信息選擇時區數據綁定,顯示時間,文本框:使用基於組合框
MainWindow.xaml.cs
private void Window_Loaded(object sender, RoutedEventArgs e)
{
ReadOnlyCollection<TimeZoneInfo> TimeZones = TimeZoneInfo.GetSystemTimeZones();
this.DataContext = TimeZones;
cmb_TZ.SelectedIndex = 1;
}
的下面是從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"/>
我的問題是:
有沒有辦法做到這一點使用數據綁定? 我能夠使用上面顯示的直接方法來做到這一點。但我想知道這個計算是否可以通過數據綁定完成?
我是新來的C#/ WPF和我試圖創建一個簡單的類,並且還使用INotifyPropertyChanged的,並指它在主窗口構造函數的類,但我不能讓即使填充組合框。
我真的很想理解和使用C#的數據綁定魔法。
你想綁定Combobox中的所有值嗎? – Balaji
組合框將有一個時區列表,我希望能夠在文本框中顯示相應的時間,具體取決於我在CB中選擇的時區。 –
「我真的很想理解和使用C#的數據綁定魔法。」如果你真的想這樣做,你應該去找一個沒有任何事件處理程序代碼的解決方案,如其他答案所示。 – Clemens