WPF Listview ModelView обновляется только один раз - PullRequest
0 голосов
/ 10 марта 2020

Я хочу обновить ListView из ModelView, он работает только один раз (при запуске программы), что неправильно. Метод BatterieApiMqtt_MessageReceived вызывается каждые две секунды, значение меняется.

Спасибо

Вот мой код

Модель

    public class AccuModel : INotifyPropertyChanged
{

    private string id;
    private string voltage;
    private string current;
    private string power;
    private string ladezustand;
    private string restkapazität;

    [JsonProperty("id")]
    public string Id
    {
        get { return id; }
        set
        {
            id = value;
            OnPropertyChanged("Id");
        }
    }

    [JsonProperty("voltage")]
    public string Voltage
    {
        get { return voltage; }
        set
        {
            voltage = value;
            OnPropertyChanged("Voltage");
        }
    }

    [JsonProperty("current")]
    public string Current
    {
        get { return current; }
        set
        {
            current = value;
            OnPropertyChanged("Current");
        }
    }

    [JsonProperty("power")]
    public string Power
    {
        get { return power; }
        set
        {
            power = value;
            OnPropertyChanged("Power");
        }
    }

    [JsonProperty("ladezustand")]
    public string Ladezustand
    {
        get { return ladezustand; }
        set
        {
            ladezustand = value;
            OnPropertyChanged("Ladezustand");
        }
    }

    [JsonProperty("restkapazität")]
    public string Restkapazität
    {
        get { return restkapazität; }
        set
        {
            restkapazität = value;
            OnPropertyChanged("Restkapazität");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

}

Модель публикации c class EnergieMonitor {[JsonProperty ("values")] publi c IList accuValues ​​{get; набор; }}

ModelView

public class AccuViewModel 
{
    private IList<AccuModel> _AccuModelsList;
    private Api.BatterieApi BatterieApiMqtt;
    public AccuViewModel()
    {
        this.BatterieApiMqtt = new Api.BatterieApi();
        BatterieApiMqtt.MessageReceived += BatterieApiMqtt_MessageReceived; 
    }

    private void BatterieApiMqtt_MessageReceived(object sender, EventArgs e)
    {
        var values = BatterieApiMqtt.EnergieMonitorValues().accuValues;
        _AccuModelsList = new List<AccuModel>();

        if (_AccuModelsList.Count > 0)
        {
            _AccuModelsList.Clear();
        }

        for (int i = 0; i < values.Count; i++)
        {
            _AccuModelsList.Add(new AccuModel());
            _AccuModelsList[i] = values[i];
        }
    }

    public IList<AccuModel> AccuModel
    {
        get { return _AccuModelsList; }
        set { _AccuModelsList = value; }
    }
}

Control.cs

 public ucWBatterie12VUebersicht()
    {
        InitializeComponent();
        AccuViewModel viewModel = new AccuViewModel();
        ListAccus.DataContext = viewModel;
    }

Control.xaml

<Grid Margin="10,90,1170,320">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <ListView Name="ListAccus" Grid.Row="1" Margin="10,10,0,10"  ItemsSource="{Binding AccuModel}" FontSize="18"  FontFamily="Arial" Foreground="WhiteSmoke" Background="Transparent" AlternationCount="2" ItemContainerStyle="{StaticResource alternateColor}">
            <ListView.View>
                <GridView>
                    <GridView.ColumnHeaderContainerStyle>
                        <Style TargetType="{x:Type GridViewColumnHeader}">
                            <Setter Property="Background" Value="#FF5B8577"/>
                            <Setter Property="Height" Value="30"/>
                        </Style>
                    </GridView.ColumnHeaderContainerStyle>
                    <GridViewColumn Header="ID" DisplayMemberBinding="{Binding Id}"  Width="50"/>
                    <GridViewColumn Header="Spannung [V]" DisplayMemberBinding="{Binding Voltage, Mode=TwoWay}"  Width="120" />
                    <GridViewColumn Header="Strom [A]" DisplayMemberBinding="{Binding Current, Mode=TwoWay}" Width="120" />
                    <GridViewColumn Header="Leistung [W]" DisplayMemberBinding="{Binding Power, Mode=TwoWay}" Width="120" />
                    <GridViewColumn Header="Ladezustand [%]" DisplayMemberBinding="{Binding Ladezustand, Mode=TwoWay}" Width="150" />
                    <GridViewColumn Header="Restkapazität [Ah]" DisplayMemberBinding="{Binding Ladezustand, Mode=TwoWay}" Width="150" />
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>

1 Ответ

0 голосов
/ 10 марта 2020
  1. Реализация интерфейса InotifyPropertychanged в вашей Viewmodel
  2. пользователя ObservableCollection вместо IList (как предложил slugster)
  3. Обновляйте свое свойство (AccumodelList) вместо поля поддержки (_AccuModelList )

Это должно решить вашу проблему.

Возможно, вы не захотите очистить список, просто назначьте новые значения (может повысить производительность ...)

...