【问题标题】:Combobox SelectionChanged event binding组合框 SelectionChanged 事件绑定
【发布时间】:2020-05-02 10:39:43
【问题描述】:

我有以下 xaml:

<DataGridTemplateColumn Header="123">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Role}"/>
    </DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
    <DataTemplate>
        <ComboBox ItemsSource="{Binding Path=DataContext.Roles, 
                  RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="SelectionChanged">
                    <i:InvokeCommandAction Command="{Binding Path = DataContext.UpdateUserCommand}" /> // bind fails there
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </ComboBox>
    </DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>

问题是我的命令没有在更改时运行,但是如果将组合框定义移出数据网格,我的命令将成功触发。好像我的绑定错了,但我不知道是什么问题。

【问题讨论】:

  • 为什么不直接将 ComboBox 的 SelectedItem 属性绑定到视图模型属性?
  • 我需要对此事件进行异步处理,对我而言,绑定到事件是唯一可能的解决方案。更改所选项目后,我想通过我的服务启动异步数据库更新
  • 您可以在视图模型中注册一个异步 PropertyChanged 事件处理程序,以对其自身的属性更改做出反应...
  • @Clemens 宁愿修改 PropertyChanged 事件引发器。绑定到您自己的事件没有多大意义
  • @Clemens 这似乎是一个更清洁的解决方案,但我没有找到任何这样做的例子,我没有太多处理事件的经验,所以我不确定如何实施这个

标签: wpf mvvm binding


【解决方案1】:

只需将 ComboBox 的 SelectedItem 属性绑定到视图模型中的 SelectedRole 属性即可。

为了在视图模型属性更改时运行异步操作,只需在视图模型中附加一个异步 PropertyChanged 事件处理程序:

public class ViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public ViewModel()
    {
        PropertyChanged += async (s, e) =>
        {
            if (e.PropertyName == nameof(SelectedRole))
            {
                await SomeAsyncAction();
            }
        };
    }

    private Role selectedRole;

    public Role SelectedRole
    {
        get { return selectedRole; }
        set
        {
            selectedRole = value;
            PropertyChanged?.Invoke(this,
                new PropertyChangedEventArgs(nameof(SelectedRole)));
        }
    }

    private async Task SomeAsyncAction()
    {
        ...
    }
}

【讨论】:

    【解决方案2】:

    你可以试试这个(不是 100% 确定它会工作,因为看不到你的所有代码)

    <i:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGrid}, Path=DataContext.UpdateUserCommand}" />
    

    【讨论】:

    • 它仍然无法正常工作。我已经试过你的方法了。现在让我看看你想查看代码的哪一部分,以便我可以编辑我的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    • 2013-03-01
    • 2016-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多