WPF 按钮未实例化
WPF Buttons not instantiating
我遇到了最奇怪的问题,快把我逼疯了。
我已经创建了一个 WPF MVVM 程序并且一切正常,但是,现在当我打开该程序并单击一个按钮时,我收到一个 System.NullReferenceException。我在发生错误且未实例化按钮的地方放置了一个断点,但是,表单显示得很好并且按钮是可点击的。事实上,none 个按钮实例化(我表单上的每个按钮都会出现相同的错误,当我在 InitializeComponent() 之后设置断点时,none 个按钮会显示在此下方 - 所有其他按钮组件显示。
这是按钮的示例代码:
MainWindow.xaml
<Button Content="A"
Command="{Binding KeyButtonClickCommand}"
Style="{StaticResource keyButtonStyle}" />
抛出错误的方法在我的ViewModel中,按钮绑定到一个命令:
private void keyButton_Click(object sender)
{
Button btn = (Button)sender;
string tempKey = "";
tempKey = btn.Content.ToString();
this.Key = tempKey;
}
InitializeComponent() 后的断点
错误后断点
就像我说的,之前工作得很好,现在就开始发毛了。
最让我担心的是,也许我做了一些不该做的事情,这可能会影响以后的项目。我只是想仔细检查它是否是那个,或者只是一个反常的事件。
谢谢。
如果我没有正确理解你的问题,那么你的 keyButton_Click 方法的参数为 null。
这很可能是因为您没有将 CommandParameter 传递给您的命令。如果要将按钮本身传递到命令中,请尝试以下 XAML.
<Button Content="A"
Command="{Binding KeyButtonClickCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource Self}}"
Style="{StaticResource keyButtonStyle}" />
我确实想指出 MVVM 的全部要点是不直接在您的 ViewModel 中与实际的 UI 层交互,当您像这样将按钮传递给 ViewModel 时,您就是在这样做。
编辑: 如评论中所述,如果您想将 "A" 作为参数传递给您的命令,您应该将其设置为您的 CommandParameter。
<Button Content="A"
Command="{Binding KeyButtonClickCommand}"
CommandParameter="A"
Style="{StaticResource keyButtonStyle}" />
我遇到了最奇怪的问题,快把我逼疯了。
我已经创建了一个 WPF MVVM 程序并且一切正常,但是,现在当我打开该程序并单击一个按钮时,我收到一个 System.NullReferenceException。我在发生错误且未实例化按钮的地方放置了一个断点,但是,表单显示得很好并且按钮是可点击的。事实上,none 个按钮实例化(我表单上的每个按钮都会出现相同的错误,当我在 InitializeComponent() 之后设置断点时,none 个按钮会显示在此下方 - 所有其他按钮组件显示。
这是按钮的示例代码:
MainWindow.xaml
<Button Content="A"
Command="{Binding KeyButtonClickCommand}"
Style="{StaticResource keyButtonStyle}" />
抛出错误的方法在我的ViewModel中,按钮绑定到一个命令:
private void keyButton_Click(object sender)
{
Button btn = (Button)sender;
string tempKey = "";
tempKey = btn.Content.ToString();
this.Key = tempKey;
}
InitializeComponent() 后的断点
错误后断点
就像我说的,之前工作得很好,现在就开始发毛了。
最让我担心的是,也许我做了一些不该做的事情,这可能会影响以后的项目。我只是想仔细检查它是否是那个,或者只是一个反常的事件。
谢谢。
如果我没有正确理解你的问题,那么你的 keyButton_Click 方法的参数为 null。
这很可能是因为您没有将 CommandParameter 传递给您的命令。如果要将按钮本身传递到命令中,请尝试以下 XAML.
<Button Content="A"
Command="{Binding KeyButtonClickCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource Self}}"
Style="{StaticResource keyButtonStyle}" />
我确实想指出 MVVM 的全部要点是不直接在您的 ViewModel 中与实际的 UI 层交互,当您像这样将按钮传递给 ViewModel 时,您就是在这样做。
编辑: 如评论中所述,如果您想将 "A" 作为参数传递给您的命令,您应该将其设置为您的 CommandParameter。
<Button Content="A"
Command="{Binding KeyButtonClickCommand}"
CommandParameter="A"
Style="{StaticResource keyButtonStyle}" />