Reputation: 123
i´ve got 2 things: second one is a list. when i´m clicking the "+1" button, a new element is createt with the name "list.Count"(so first one is 1, 2, 3, 4...). this is working very good. but for the first thing i wanna have only the vurrent value of the "Text"(from the current newest object in the list). But: i do not only want a counter. Maybe you can unterstand better if you check out my code:
<StackLayout>
<StackLayout>
<StackLayout Orientation="Horizontal" >
<Label Text="Erg:" HorizontalOptions="StartAndExpand" VerticalOptions="StartAndExpand" />
<Label Text="{Binding Path=Nummer, Source=Num}" HorizontalOptions="EndAndExpand" VerticalOptions="StartAndExpand" /> *
</StackLayout>
<Button Text="+1" Command="{Binding CountUpCommand}" /> **
<Button Text="Erg x Erg" />
</StackLayout>
<Label Text="--------------" />
<StackLayout>
<ListView ItemsSource="{Binding Nummer}"> **
<ListView.ItemTemplate>
<DataTemplate>
<TextCell
Text="{Binding Num}" **
/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</StackLayout>
so my question is at the Line with only one * at the end. the other 3 lines with two ** are working. what do i have to do to get the right Binding-Path or -Statment or something like this, to get the number shown up at labelsText ? i think there´s something missing like "itemsource"..
so here s the code from Itemsource (from My CounterVM):
public ObservableCollection<NumberViewModel> Nummer { get; private set; } = new ObservableCollection<NumberViewModel>();
public ICommand CountUpCommand { get; private set; }
public CounterViewModel()
{
CountUpCommand = new Command(CountUp);
}
public void CountUp()
{
int newNumber = Nummer.Count + 1;
Nummer.Add(new NumberViewModel { Num = newNumber});
}
and here the NumverVM, same code as in number.cs:
public class NumberViewModel : BaseViewModel
{
public int Num { get; set; }
}
Upvotes: 0
Views: 145
Reputation: 2834
You can add a Property inside your ViewModel to get the correct value:
public class CounterViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
public string LastItemsText => Nummer.Last()?.Num.ToString();
public ObservableCollection<NumberViewModel> Nummer { get; private set; } = new ObservableCollection<NumberViewModel>();
public ICommand CountUpCommand { get; private set; }
public CounterViewModel()
{
CountUpCommand = new Command(CountUp);
}
public void CountUp()
{
int newNumber = Nummer.Count + 1;
Nummer.Add(new NumberViewModel { Num = newNumber});
PropertyChanged(this, new PropertyChangedEventArgs(nameof(LastItemsText));
}
}
And instead of
<Label Text="{Binding Path=Nummer, Source=Num}"
do this:
<Label Text="{Binding LastItemsText}"
Upvotes: 1