Am o ListBox
, ca atare:
<ListBox
//other stuff
ItemsSource="{Binding ViewModels, UpdateSourceTrigger=PropertyChanged}"
SelectedItem="{Binding SelectedThing, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="Purple" />
</Trigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
ViewModel.cs:
public SomeType SelectedThing
{
get => selectedThing;
set => //set with INotifyPropertyChanged
}
public ObservableCollection<SomeType> ViewModels
{
get => viewModels;
set => //set with INotifyPropertyChanged
}
E posibil ca SelectedThing
este definit în ViewModel
când încărcați aplicația, așa că am vrut să fie decorate în mod corespunzător.
It works mare atunci când am deschis aplicația și apoi faceți clic pe un element, dar cum poate fi stilul aplicată pe sarcină?
Am incercat cu:
<Style.Triggers>
<DataTrigger Binding="{Binding IsEnabled, RelativeSource={RelativeSource Mode=Self}}" Value="True">
<Setter Property="Background" Value="Purple" />
</DataTrigger>
</Style.Triggers>
Dar fiecare element al ListBox
este activat, astfel încât se aplică pentru fiecare element pe sarcină.
EDIT:
După depanare un pic, am aflat că, atunci când setarea SelectedThing
pe de sarcină, SelectedItem
rămâne null
.
EDIT:
Aici este OnLoaded
metoda în ViewModel
, unde sunt cadru SelectedThing
dacă utilizatorul a selectat-o în timp ce anterior, folosind aplicația. Scopul este de a menține selecție după închiderea și redeschiderea aplicația.
public IAsyncRelayCommand OnLoadedCommand { get; set; }
În constructor:
OnLoadedCommand = new AsyncRelayCommand(OnLoaded);
În Vedere:
<b:Interaction.Triggers>
<b:EventTrigger EventName="Loaded">
<b:InvokeCommandAction Command="{Binding OnLoadedCommand}" />
</b:EventTrigger>
</b:Interaction.Triggers>
Metoda actuală:
public async Task OnLoaded()
{
//other stuff
if (App.Current.Properties.Contains(nameof(SelectedThing)))
{
var selected = JsonConvert.DeserializeObject<SomeType>(App.Current.Properties[nameof(SelectedThing)].ToString());
SelectedThing = selected;
}
}