Mám ListBox
ako:
<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
}
Je možné, že SelectedThing
je definovaný v ViewModel
pri načítaní aplikácie, a tak som sa to má byť štylizované spôsobom.
Funguje to skvele, keď som chcete aplikáciu otvoriť, a potom kliknite na položku, ale ako je možné, že štýl sa aplikuje na načítať?
Snažil som sa s:
<Style.Triggers>
<DataTrigger Binding="{Binding IsEnabled, RelativeSource={RelativeSource Mode=Self}}" Value="True">
<Setter Property="Background" Value="Purple" />
</DataTrigger>
</Style.Triggers>
Ale každá položka ListBox
je zapnutá, tak platí to, aby každá položka na zaťaženie.
ÚPRAVA:
Po ladenie trochu som zistil, že pri nastavovaní SelectedThing
na zaťaženie, SelectedItem
zostáva null
.
ÚPRAVA:
Tu je OnLoaded
metódy v ViewModel
tam , kde som nastavenie SelectedThing
ak používateľ vybral to, keď predtým pomocou aplikácie. Účelom je, aby výber po zatváraní a otváraní aplikácie.
public IAsyncRelayCommand OnLoadedCommand { get; set; }
V constructor:
OnLoadedCommand = new AsyncRelayCommand(OnLoaded);
V Okne:
<b:Interaction.Triggers>
<b:EventTrigger EventName="Loaded">
<b:InvokeCommandAction Command="{Binding OnLoadedCommand}" />
</b:EventTrigger>
</b:Interaction.Triggers>
Skutočné metóda:
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;
}
}