C#组合框-通过SelectionChanged调用DataContext中的函数
我有一个如下所示的组合框:C#组合框-通过SelectionChanged调用DataContext中的函数,c#,wpf,xaml,combobox,C#,Wpf,Xaml,Combobox,我有一个如下所示的组合框: <ComboBox Text="Choose program" Margin="5" Grid.Row="0" Grid.Column="1" ItemsSource="{Binding ProgramsToChooseFrom}" SelectedValue="{Binding CurrentProgId, Mode=TwoWay}" SelectedValuePath="Id" DisplayMemberPath="Prog
<ComboBox Text="Choose program" Margin="5" Grid.Row="0" Grid.Column="1"
ItemsSource="{Binding ProgramsToChooseFrom}"
SelectedValue="{Binding CurrentProgId, Mode=TwoWay}"
SelectedValuePath="Id"
DisplayMemberPath="ProgName" SelectionChanged="Function_SelectionChanged">
</ComboBox>
我试图在选择更改时运行一个函数(以更新另一个组合框的值)。为此,我使用了SelectionChanged=“Function\u SelectionChanged”
,但显然这是在窗口的代码中查找函数,因为现在Function\u SelectionChanged
是在窗口的数据上下文中实现的,我得到了错误:
“CourseEditorWindow”不包含的定义
“功能选择已更改”且无扩展方法
“Function_SelectionChanged”接受类型为的第一个参数
找不到“CourseEditorWindow”(是否缺少using指令
或程序集引用?)
如何从组合框(在窗口的DataContext中定义)通过XAML调用函数?基本上,每当选择发生更改时,我都会尝试调用
\u courseViewModel.Function\u SelectionChanged
。我建议使用另一种策略,而不是查找您应该在视图模型(或数据上下文)中检查任何修改的事件对象。实际上,您需要在CourseViewModel
中调用CurrentProgId
的setter中的方法,因为每当组合框的选择发生更改时都会调用该方法,这类似于:
private int _currentProgId;
public int CurrentProgId
{
get { return _currentProgId; }
set
{
_currentProgId= value;
CallSomeMethod();
}
}
您需要在ViewModel的
CurrentProgId
的setter中执行一些操作,并删除SelectionChanged
事件,因为每当在ComboBox中更改选择时,都会调用setter尝试使用SelectedItem
为您的ComboBox
执行设置。然后通过VM
处理更改。
private int _currentProgId;
public int CurrentProgId
{
get { return _currentProgId; }
set
{
_currentProgId= value;
CallSomeMethod();
}
}