Usercontrol INTERFACE do usuário não alterar

0

Pergunta

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>

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

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'

Olá! Quando se há uma função que chama SearchView.TimerSearch("x")

Eu acho que UserControl mostra a contagem que é devolvido a partir de SearchView.TimerSearch("x")

Mas não trabalho como eu esperava.

ligação log diz que mudou para 2. mas mostra " 0 " e nunca mudou!

Alguém pode me ajudar?

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

Melhor resposta

1

Você está ligando para o aninhados Count propriedade da coleção. Mas já que você está substituindo a coleção completa, o Count propriedade efetivamente não muda como a instância de coleção alteração não será detectada pelo Binding. Em outras palavras, o Binding é a escuta de uma Count alterado evento, mas esse evento nunca é levantada, porque a instância de coleção em si foi alterado de vez.
É geralmente recomendável para usar sempre a mesma instância de coleção em um enlace de dados de contexto: limpar a coleção e adicionar a nova gama de itens.

O próximo é o seu método assíncrono TimerSearch: atualmente, não é esperada e não retornar um Task!
Lembre-se: async void é apenas permitido para manipuladores de eventos. Caso contrário, um void o método deve sempre ser convertida para retornar Task.

Quando você await um método que você deve await o completo chamada de árvore (todos os chamadores também): async Task em todos os lugares.

// 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);
    }
}

No caso de response.ResponseData retorna um List<T>, você pode substituir o foreach loop com uma chamada de List<T>.ForEach método para compactar o código:

response.ResponseData.ForEach(SearchedUsers.Add);

De seguida, converter a chamada de método para retornar um Task muito e await o TimerSearch chamada de método:

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

Finalmente, evitar a definição do DataContext em seu controle. Isso limita a usabilidade do controle para ser utilizado apenas no contexto especial.

Geralmente, você não tem um modelo de modo de exibição de classe para cada controle, este não é como você criar controles. Os controles devem ser desenvolvidas independentes a partir de um modelo de modo de exibição de classe.
No seu caso, o controle teria uma UserCount propriedade de dependência, que, mais tarde, você pode ligar para uma visão externa do modelo. Internamente, o TextBox gostaria de vincular a UserCount propriedade de dependência.

2021-11-22 17:27:32

Em outros idiomas

Esta página está em outros idiomas

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