问题描述
我目前正在开发C#WPF应用程序,遇到一个非常奇怪的错误。我从使用多个窗口转向使用UserControls,并体验了一种非常奇怪的行为。我有一个名为DataEntryControl
的UserControl,它带有一个带有SelectionChanged触发器的ComboBox,XAML如下所示:
<StackPanel Grid.Row="1" Grid.Column="3" VerticalAlignment="Center">
<ComboBox Name="cbEntry" Width="200" HorizontalAlignment="Left" SelectionChanged="cbEntry_SelectionChanged">
<ComboBoxItem Content="Auto - Benziner" IsSelected="True" />
<ComboBoxItem Content="Auto - Diesel" />
<ComboBoxItem Content="Auto - Hybrid" />
<ComboBoxItem Content="Auto - Elektro" />
<ComboBoxItem Content="ÖPNV" />
<ComboBoxItem Content="Fahrrad" />
<ComboBoxItem Content="E-Bike" />
<ComboBoxItem Content="Homeoffice" />
</ComboBox>
</StackPanel>
DataEntryControl的C#代码如下(摘录):
public partial class DataEntryControl : UserControl
{
Benutzer currentUser = MainWindow.currentUser;
DBContext db = new DBContext();
public DataEntryControl()
{
InitializeComponent();
}
private void cbEntry_SelectionChanged(object sender,SelectionChangedEventArgs e)
{
if (currentUser == null) return;
double saved = (db.Anreisetypen.Find(currentUser.AnreisetypenID).co2ProKm * currentUser.distanz -
db.Anreisetypen.Find(MainWindow.fahrzeugID((cbEntry.SelectedItem as ComboBoxItem).Content.ToString())).co2ProKm * currentUser.distanz);
tbSaved.Text = "Dadurch gespart:\n" + saved.ToString() + "g CO2";
tbTotal.Text = "Einsparung gesamt:\n" + (currentUser.ersparnis + saved).ToString() + "g CO2";
}
}
当用户单击MainWindow中的按钮时创建了控件,但是在这里,根据我激活UserControl的方式,我遇到了两种非常奇怪的行为。
版本1:
public void dataEntryClick(object sender,RoutedEventArgs e)
{
ControlGrid.Children.Clear();
ControlGrid.Children.Add(new DataEntryControl());
}
这将导致在创建控件时立即调用cbEntry_SelectionChanged
方法,并为tbSaved
和tbTotal
(两个TextBox)抛出NullPointerException。我不知道这怎么会发生?如果尚未加载所属的XAML,如何触发事件触发器?
在此之后,我想到可以检查那些对象是否为空,这消除了错误,但是没有为这两个文本框设置Text,这很烦人。我可以通过忽略事件的第一次触发后模拟点击来解决此问题,我只是很好奇。
我尝试的另一件事是在加载DataEntryControl
实例之前创建MainWindow
实例(在创建public partial class MainWindow: Window {
DataEntryControl d { get; set; } = new DataEntryControl();
//... constructor and stuff
public void dataEntryClick(object sender,RoutedEventArgs e)
{
ControlGrid.Children.Clear();
ControlGrid.Children.Add(d);
}
}
实例时),使MainWindow中的C#代码看起来像这样:
版本2:
cbEntry_SelectionChanged
但这会导致DataEntryWindow
从不被触发。初始化时不会触发它(这很好),但是更改选择时也不会触发它,这很奇怪,因为它侦听SelectionChanged事件。
就像我以前写的:如果ComboBox或TextBoxes为空,我只是中止选择功能,为此问题我建立了一个不太好的解决方法-这使我有99%的功能想实现,但是imo没有什么意义,因此我仍然想知道为什么WPF在这种情况下会表现得如此。当我使用DataEntryControl
而不是#!/bin/bash
TOKEN_JSON_RESPONSE='
{
"access_token":"eyJxxxxxxxx","token_type":"bearer","expires_in":3600
}'
echo 'The token response is ' $TOKEN_JSON_RESPONSE
ACCESS_TOKEN=$(echo $TOKEN_JSON_RESPONSE | jq -j '.access_token')
echo 'The access token is '$ACCESS_TOKEN
时,也没有遇到这个问题,这使它变得更加奇怪。希望有人可以帮我,谢谢!
解决方法
您描述的第一个问题是因为您在XAML中:
<ComboBoxItem Content="Auto - Benziner" IsSelected="True" />
这将导致ComboBox在创建后立即选择第一项,从而导致选择从“ Null”更改为第一项。