Usercontrol INTERFACE ne change pas

0

La question

UserControl

  <UserControl x:Class="NolowaFrontend.Views.MainViews.SearchView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:NolowaFrontend.Views.MainViews"
             xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"
             xmlns:designTime="clr-namespace:NolowaFrontend.Views"
             mc:Ignorable="d" Name="_this"
             d:DesignHeight="300" d:DesignWidth="350" d:Background="White">   
    <Grid>
        <TextBlock Text="{Binding SearchedUsers.Count, diag:PresentationTraceSources.TraceLevel=High}" Foreground="Red" FontSize="20"/>
    </Grid>
</UserControl>

Le code-behind

public partial class SearchView : UserControl
{
    private readonly SearchVM _searchVM;

    public SearchView(User user)
    {
        InitializeComponent();

        _searchVM = new SearchVM(user); ;

        DataContext = _searchVM;
    }

    public void TimerSearch(string text)
    {
        _searchVM.TimerSearch(text);
    }
}

ViewModel

public class SearchVM : ViewModelBase
{
    private readonly User _user;
    private readonly ISearchService _searchService;

    private ObservableCollection<SearchedUser> _searchedUsers = new ObservableCollection<SearchedUser>();

    public ObservableCollection<SearchedUser> SearchedUsers
    {
        get { return _searchedUsers; }
        set { _searchedUsers = value; OnPropertyChanged(); }
    }

    public SearchVM(User user)
    {
        _user = user;
        _searchService = new SearchService();
    }

    public async void TimerSearch(string text)
    {
        var response = await _searchService.SearchUser(text);

        var data = response.ResponseData;

        SearchedUsers = data.ToObservableCollection(); 
    }
}

bindig journal

System.Windows.Data Warning: 67 : BindingExpression (hash=11842506): Resolving source 
System.Windows.Data Warning: 70 : BindingExpression (hash=11842506): Found data context element: TextBlock (hash=56511253) (OK)
System.Windows.Data Warning: 78 : BindingExpression (hash=11842506): Activate with root item SearchVM (hash=52539597)
System.Windows.Data Warning: 108 : BindingExpression (hash=11842506):   At level 0 - for SearchVM.SearchedUsers found accessor RuntimePropertyInfo(SearchedUsers)
System.Windows.Data Warning: 104 : BindingExpression (hash=11842506): Replace item at level 0 with SearchVM (hash=52539597), using accessor RuntimePropertyInfo(SearchedUsers)
System.Windows.Data Warning: 101 : BindingExpression (hash=11842506): GetValue at level 0 from SearchVM (hash=52539597) using RuntimePropertyInfo(SearchedUsers): ObservableCollection`1 (hash=49313939 Count=0)
System.Windows.Data Warning: 108 : BindingExpression (hash=11842506):   At level 1 - for ObservableCollection`1.Count found accessor RuntimePropertyInfo(Count)
System.Windows.Data Warning: 104 : BindingExpression (hash=11842506): Replace item at level 1 with ObservableCollection`1 (hash=49313939 Count=0), using accessor RuntimePropertyInfo(Count)
System.Windows.Data Warning: 101 : BindingExpression (hash=11842506): GetValue at level 1 from ObservableCollection`1 (hash=49313939 Count=0) using RuntimePropertyInfo(Count): '0'
System.Windows.Data Warning: 80 : BindingExpression (hash=11842506): TransferValue - got raw value '0'
System.Windows.Data Warning: 84 : BindingExpression (hash=11842506): TransferValue - implicit converter produced '0'
System.Windows.Data Warning: 89 : BindingExpression (hash=11842506): TransferValue - using final value '0'
System.Windows.Data Warning: 56 : Created BindingExpression (hash=29516363) for Binding (hash=55475379) BindingExpression:Path=SearchedUsers.Count; DataItem=null; 
System.Windows.Data Warning: 58 :  Path: 'SearchedUsers.Count'
System.Windows.Data Warning: 60 : BindingExpression (hash=29516363): Default mode resolved to OneWay
System.Windows.Data Warning: 61 : BindingExpression (hash=29516363): Default update trigger resolved to PropertyChanged
System.Windows.Data Warning: 62 : BindingExpression (hash=29516363): Attach to System.Windows.Controls.TextBlock.Text (hash=35990092)
System.Windows.Data Warning: 67 : BindingExpression (hash=29516363): Resolving source 
System.Windows.Data Warning: 70 : BindingExpression (hash=29516363): Found data context element: TextBlock (hash=35990092) (OK)
System.Windows.Data Warning: 71 : BindingExpression (hash=29516363): DataContext is null
System.Windows.Data Warning: 65 : BindingExpression (hash=29516363): Resolve source deferred
System.Windows.Data Warning: 67 : BindingExpression (hash=29516363): Resolving source 
System.Windows.Data Warning: 70 : BindingExpression (hash=29516363): Found data context element: TextBlock (hash=35990092) (OK)
System.Windows.Data Warning: 78 : BindingExpression (hash=29516363): Activate with root item SearchVM (hash=64320678)
System.Windows.Data Warning: 107 : BindingExpression (hash=29516363):   At level 0 using cached accessor for SearchVM.SearchedUsers: RuntimePropertyInfo(SearchedUsers)
System.Windows.Data Warning: 104 : BindingExpression (hash=29516363): Replace item at level 0 with SearchVM (hash=64320678), using accessor RuntimePropertyInfo(SearchedUsers)
System.Windows.Data Warning: 101 : BindingExpression (hash=29516363): GetValue at level 0 from SearchVM (hash=64320678) using RuntimePropertyInfo(SearchedUsers): ObservableCollection`1 (hash=42592467 Count=0)
System.Windows.Data Warning: 107 : BindingExpression (hash=29516363):   At level 1 using cached accessor for ObservableCollection`1.Count: RuntimePropertyInfo(Count)
System.Windows.Data Warning: 104 : BindingExpression (hash=29516363): Replace item at level 1 with ObservableCollection`1 (hash=42592467 Count=0), using accessor RuntimePropertyInfo(Count)
System.Windows.Data Warning: 101 : BindingExpression (hash=29516363): GetValue at level 1 from ObservableCollection`1 (hash=42592467 Count=0) using RuntimePropertyInfo(Count): '0'
System.Windows.Data Warning: 80 : BindingExpression (hash=29516363): TransferValue - got raw value '0'
System.Windows.Data Warning: 84 : BindingExpression (hash=29516363): TransferValue - implicit converter produced '0'
System.Windows.Data Warning: 89 : BindingExpression (hash=29516363): TransferValue - using final value '0'
System.Windows.Data Warning: 95 : BindingExpression (hash=11842506): Got PropertyChanged event from SearchVM (hash=52539597)
System.Windows.Data Warning: 101 : BindingExpression (hash=11842506): GetValue at level 0 from SearchVM (hash=52539597) using RuntimePropertyInfo(SearchedUsers): ObservableCollection`1 (hash=53428882 Count=2)
System.Windows.Data Warning: 105 : BindingExpression (hash=11842506):   Item at level 1 has same type - reuse accessor RuntimePropertyInfo(Count)
System.Windows.Data Warning: 104 : BindingExpression (hash=11842506): Replace item at level 1 with ObservableCollection`1 (hash=53428882 Count=2), using accessor RuntimePropertyInfo(Count)
System.Windows.Data Warning: 101 : BindingExpression (hash=11842506): GetValue at level 1 from ObservableCollection`1 (hash=53428882 Count=2) using RuntimePropertyInfo(Count): '2'
System.Windows.Data Warning: 80 : BindingExpression (hash=11842506): TransferValue - got raw value '2'
System.Windows.Data Warning: 84 : BindingExpression (hash=11842506): TransferValue - implicit converter produced '2'
System.Windows.Data Warning: 89 : BindingExpression (hash=11842506): TransferValue - using final value '2'

Salut! Si il y a une fonction qui s'appelle SearchView.TimerSearch("x")

Je pense que UserControl indique le nombre qui est retourné à partir de SearchView.TimerSearch("x")

Mais ce n'est pas de travail, comment je m'attends.

la liaison journal dit qu'il est passé à 2. mais il indique " 0 " et n'a jamais changé!

Quelqu'un peut-il m'aider?

data-binding mvvm wpf
2021-11-22 16:05:54
1

La meilleure réponse

1

Vous êtes de la liaison à la imbriquée Count propriété de la collection. Mais puisque vous êtes le remplacement de la collection complète, la Count propriété effectivement ne change pas comme l'instance de la collection, le changement n'est pas détecté par le Binding. En d'autres termes, l' Binding est à l'écoute pour un Count un événement a changé, mais cet événement n'est jamais posée, parce que l'instance de la collection elle-même a changé de place.
Il est généralement recommandé de toujours utiliser la même instance de la collection dans une liaison de données contexte: effacer la collecte et l'ajout de la nouvelle gamme d'articles.

La prochaine est votre méthode async TimerSearch: il est actuellement ne l'attend pas et ne retourne pas Task!
Souvenez-vous: async void est seulement autorisé pour les gestionnaires d'événements. Sinon, un void la méthode doit toujours être convertie pour revenir Task.

Lorsque vous await une méthode que vous devez await l'appel complet de l'arbre (tous les appelants trop): async Task partout.

// Make method return Task
public async Task TimerSearchAsync(string text)
{
    var response = await _searchService.SearchUser(text);

    SearchedUsers.Clear();
    foreach (var data in response.ResponseData)
    {
       SearchedUsers.Add(data);
    }
}

En cas response.ResponseData retourne un List<T>vous pouvez remplacer le foreach boucle avec un appel de la List<T>.ForEach méthode pour compacter le code:

response.ResponseData.ForEach(SearchedUsers.Add);

Ensuite, convertir la méthode d'appel à renvoyer une Task trop et await l' TimerSearch appel de la méthode:

// Declare method async and return a Task
public async Task TimerSearcAsynch(string text)
{
    await _searchVM.TimerSearchAsync(text);
}

Enfin, évitez de régler l' DataContext dans votre contrôle. Cela limite les possibilités d'utilisation de la commande pour être utilisé uniquement dans le contexte particulier.

Généralement, vous n'avez pas un modèle de vue de la classe pour chaque contrôle, ce n'est pas la façon dont vous concevez des contrôles. Les contrôles doivent être développés indépendamment à partir d'un modèle de vue de classe.
Dans votre cas, le contrôle aurait un UserCount propriété de dépendance, qui, plus tard, vous pouvez lier à un point de vue externe modèle. En interne, l' TextBox se lient à l' UserCount propriété de dépendance.

2021-11-22 17:27:32

Dans d'autres langues

Cette page est dans d'autres langues

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................