我有以下的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>
问题是我的命令在改变时没有运行 但如果把组合框定义从数据网格中移出,我的命令就会成功执行。好像是我的绑定出了问题,但我不知道是哪里出了问题,我有以下的xaml:我的命令没有在变化时运行,但如果把组合框的定义从数据网格中移出,我的命令就成功了。
只要绑定组合框的 SelectedItem
属性为 SelectedRole
属性的视图模型中。
为了在视图模型属性改变时运行异步操作,只需在视图模型中附加一个async 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()
{
...
}
}
你可以试试这个(不是100%确定会成功,因为不能看到你所有的代码)
<i:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGrid}, Path=DataContext.UpdateUserCommand}" />