C# ComboBox - 通过 SelectionChanged 调用 DataContext 中的函数



我有一个看起来像这样的组合框:

<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>

该窗口是具有CourseViewModel数据上下文的CourseEditorWindow

_courseViewModel = new CourseViewModel(_model);
_editorView = new CourseEditorWindow();
_editorView.DataContext = _courseViewModel;
_editorView.Show();

我正在尝试在更改选择时运行一个函数(以更新另一个组合框的值(。为此,我正在使用SelectionChanged="Function_SelectionChanged"但显然这会在窗口的代码中查找该函数,因为现在Function_SelectionChanged是在窗口的 DataContext 中实现的,并且我收到错误:

"课程编辑器窗口"不包含 "Function_SelectionChanged"且无扩展方法 'Function_SelectionChanged'接受类型的第一个参数 可以找到"课程编辑器窗口"(您是否缺少使用指令 还是程序集引用?

如何通过 XAML 从窗口的数据上下文中定义的组合框调用函数?基本上,每当选择更改时,我都会尝试调用_courseViewModel.Function_SelectionChanged

您实际上需要在CourseViewModelCurrentProgId setter 中调用该方法,因为每当组合框的选择发生变化时都会调用该方法,如下所示:

private int _currentProgId;
public int CurrentProgId
{
  get { return _currentProgId; }
  set
  {
    _currentProgId= value;
    CallSomeMethod();
  }
}

我建议使用另一种策略,而不是寻找事件,您应该在 CurrentProgId 属性中检查视图模型(或 DataContext(对象中的任何修改。

最新更新