TargetUpdated и SourceUpdated не запускаются после ObservableCollection.Add - PullRequest
0 голосов
/ 16 июня 2020

У меня метод OnBindingOccured запускается при событиях SourceUpdated и TargetUpdated, при добавлении нового элемента в список JobSpecialConfigurations и последующем вызове OnPropertyChanged OnBindingOccured не срабатывает. Почему он не срабатывает?

В ViewModel

public ICommand BindingOccuredCommand { get; set; }
public ICommand AddSpecialConfigCommand { get; set; }

public MainViewModel()
{
     AddSpecialConfigCommand = new DelegateCommand(OnAddSpecialConfig);
     BindingOccuredCommand = new DelegateCommand<System.Windows.Data.DataTransferEventArgs>(OnBindingOccured);
}

private void OnBindingOccured(DataTransferEventArgs dataTransfer)
{
    //Some Work
}

private async void OnAddSpecialConfig()
{
    var specialConfig = new JobSpecialConfiguration
    {
        SCEnum = null,
        SCValue = string.Empty,
        JobId = Job.Id
    };

    var specialConfigWrapper = new JobSpecialConfigurationWrapper(specialConfig)
    {
        Job = Job
    };
    Job.Model.JobSpecialConfigurations.Add(specialConfig);
    Job.JobSpecialConfigurations.Add(specialConfigWrapper);
    specialConfigWrapper.OnPropertyChanged(nameof(JobSpecialConfigurationWrapper.SCEnum));
    specialConfigWrapper.OnPropertyChanged(nameof(JobSpecialConfigurationWrapper.SCValue));
}

XAML

<Grid>
        <telerik:EventToCommandBehavior.EventBindings>
            <telerik:EventBinding EventName="SourceUpdated" Command="{Binding BindingOccuredCommand}" PassEventArgsToCommand="True" />
            <telerik:EventBinding EventName="TargetUpdated" Command="{Binding BindingOccuredCommand}" PassEventArgsToCommand="True" />
        </telerik:EventToCommandBehavior.EventBindings>

        <ItemsControl ItemsSource="{Binding Job.JobSpecialConfigurations}" Margin="3">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition/>
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition/>
                            <ColumnDefinition/>
                            <ColumnDefinition Width="Auto"/>
                        </Grid.ColumnDefinitions>

                        <telerik:RadComboBox 
                                ClearSelectionButtonVisibility="Visible" 
                                TextSearchMode="Contains"
                                IsEditable="True"
                                IsReadOnly="True"
                                OpenDropDownOnFocus="True"
                                Grid.Row="1" Grid.Column="0"
                                ClearSelectionButtonContent="Clear Selection" 
                                IsTextSearchEnabled="True"
                                ItemsSource="{Binding Source={StaticResource enmSESpecialConfigurationEnum}}"
                                Margin="10"  
                                SelectedValue="{Binding SCEnum, UpdateSourceTrigger=LostFocus, NotifyOnSourceUpdated=True, NotifyOnTargetUpdated=True}"
                                SelectedValuePath="SpecialConfiguration"
                                DisplayMemberPath="ShortDescription">
                            <telerik:EventToCommandBehavior.EventBindings>
                                <telerik:EventBinding EventName="LostFocus" 
                                Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:JobShippingView}}, Path=DataContext.OpenSpecificControlCommand}"
                                CommandParameter="{Binding}" />
                            </telerik:EventToCommandBehavior.EventBindings>
                        </telerik:RadComboBox>

                        <TextBox Grid.Column="1" Grid.Row="1" Margin="8" Text="{Binding SCValue, Mode=TwoWay,UpdateSourceTrigger=LostFocus, NotifyOnSourceUpdated=True, NotifyOnTargetUpdated=True}"
                             Visibility="{Binding IsScTextBoxVisible,FallbackValue=Collapsed,Converter={StaticResource BooleanToVisibilityConverter},Mode=OneWay,UpdateSourceTrigger=PropertyChanged}">
                        </TextBox>

                        <telerik:RadNumericUpDown Minimum="0" Margin="8 0 8 10" Name="NumericAllCars" Grid.Row="1"
                                              Grid.Column="1"
                                              Value="{Binding SCValue, Mode=TwoWay, UpdateSourceTrigger=LostFocus, NotifyOnSourceUpdated=True, NotifyOnTargetUpdated=True, Converter={StaticResource StringToDoubleConverter}}"
                                              ShowButtons="False"
                                              Visibility="{Binding IsScNumericVisible,FallbackValue=Collapsed,Converter={StaticResource BooleanToVisibilityConverter},Mode=OneWay,UpdateSourceTrigger=PropertyChanged}">
                            <telerik:RadNumericUpDown.NumberFormatInfo>
                                <globalization:NumberFormatInfo NumberDecimalDigits="2"/>
                            </telerik:RadNumericUpDown.NumberFormatInfo>
                        </telerik:RadNumericUpDown>

                        <telerik:RadDatePicker Grid.Row="1" Grid.Column="1" 
                                           SelectedDate="{Binding SCValue, Mode=TwoWay, UpdateSourceTrigger=LostFocus, NotifyOnSourceUpdated=True, NotifyOnTargetUpdated=True, Converter={StaticResource StringToDateConverter}}"
                                           Margin="8,0,8,10"
                                           Visibility="{Binding IsScDatePickerVisible,FallbackValue=Collapsed,Converter={StaticResource BooleanToVisibilityConverter},Mode=OneWay,UpdateSourceTrigger=PropertyChanged}">
                        </telerik:RadDatePicker>

                        <CheckBox  Grid.Row="1" Grid.Column="1" IsChecked="{Binding SCValue, NotifyOnSourceUpdated=True, NotifyOnTargetUpdated=True}" Content="Is Checked" IsEnabled="False"
                                   Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:JobShippingView}}, Path=DataContext.ShowGroupBoxesCommand}" CommandParameter="{Binding Job}"
                                   Visibility="{Binding IsScCheckBoxVisible,FallbackValue=Collapsed,Converter={StaticResource BooleanToVisibilityConverter},Mode=OneWay,UpdateSourceTrigger=PropertyChanged}">
                        </CheckBox>

                        <Button Grid.Column="2" Grid.Row="1" BorderThickness="0" Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" Margin="10 10 10 0" Cursor="Hand" Focusable="False"
                            Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:JobShippingView}}, Path=DataContext.RemoveSpecialConfigCommand}"
                            CommandParameter="{Binding}">
                            <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
                                <materialDesign:PackIcon Kind="DeleteCircle" HorizontalAlignment="Center" VerticalAlignment="Center" Width="20" Height="20"/>
                            </StackPanel>
                        </Button>
                    </Grid>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
</Grid>

Я пробовал обходной путь для решения этой проблемы, я вызываю асинхронный сон перед OnPropertyChanged позвоните, как показано ниже:

....
Job.Model.JobSpecialConfigurations.Add(specialConfig);
Job.JobSpecialConfigurations.Add(specialConfigWrapper);
await Task.Run(() => System.Threading.Thread.Sleep(100)); // When adding this line it fire the event
specialConfigWrapper.OnPropertyChanged(nameof(JobSpecialConfigurationWrapper.SCEnum));
specialConfigWrapper.OnPropertyChanged(nameof(JobSpecialConfigurationWrapper.SCValue));

Так что это как-то сбивает с толку, почему мне нужно ждать 100 миллисекунд и любую альтернативу для этого.

...