NPadrutt NPadrutt - 22 days ago 6
C# Question

SelectedItem not updated

I have a UWP app with a listbox who is bound to a List of Enums to display the different options with a radio button.

What I want, is that when I select an item (for example yearly), that on the SelectedCategory the BudgetPeriod is changed to the enum yearly. What I tried is the following:

My Listbox:

<ListBox Margin="0,0,0,12"
ItemsSource="{Binding BudgetPeriods}"
SelectedItem="{Binding SelectedCategory.BudgetPeriod}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<RadioButton Content="{TemplateBinding Content}" IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsSelected}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>

Selected Category Property:
public CategoryViewModel SelectedCategory
{
get { return selectedCategory; }
set
{
selectedCategory = value;
RaisePropertyChanged();
}
}


List of enums:

public List<BudgetPeriod> BudgetPeriods => new List<BudgetPeriod>
{
BudgetPeriod.Monthly,
BudgetPeriod.Yearly
};


Unfortunately the Propety in SelectedCategory.BudgetPeriod is always Monthly (The first selection) and is not changing when I select something else.

The project is open source, so you can checkout the whole code aswell: https://github.com/NPadrutt/MoneyFox.Windows/tree/budget

Links to the relevant classes:
View Model:
https://github.com/NPadrutt/MoneyFox.Windows/blob/budget/Src/MoneyFox.Business/ViewModels/ModifyCategoryViewModel.cs

Model:
https://github.com/NPadrutt/MoneyFox.Windows/blob/budget/Src/MoneyFox.Foundation/DataModels/CategoryViewModel.cs

View:
https://github.com/NPadrutt/MoneyFox.Windows/blob/budget/Src/MoneyFox.Windows/Views/ModifyCategoryView.xaml

View (code Behind):
https://github.com/NPadrutt/MoneyFox.Windows/blob/budget/Src/MoneyFox.Windows/Views/ModifyCategoryView.xaml.cs

Android Layout:
https://github.com/NPadrutt/MoneyFox.Windows/blob/budget/Src/MoneyFox.Droid/Resources/layout/activity_modify_category.axml

Answer

You should set the binding in "TwoWay" mode :

  SelectedItem="{Binding SelectedCategory.BudgetPeriod, Mode=TwoWay}">