ฉันมี ListBox
อย่างที่มี:
<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
}
มันเป็นไปได้นั้น SelectedThing
คือมีนิยามอยู่ ViewModel
ตอนที่กำลังโหลดแอพฯดังนั้นฉันต้องการให้มันเป็น styled กว่านี้ละกัน
มันทำงานได้เยี่ยมตอนที่ฉันเปิดแอพฯและจากนั้นคลิกบนรายการแต่ยังสามารถที่ถูกปรับใช้รูปแบบบนรถโหลด?
ฉันพยายามด้วย:
<Style.Triggers>
<DataTrigger Binding="{Binding IsEnabled, RelativeSource={RelativeSource Mode=Self}}" Value="True">
<Setter Property="Background" Value="Purple" />
</DataTrigger>
</Style.Triggers>
แต่ทุกรายการของ ListBox
กเปิดใช้ตัวเลือกดังนั้นมันใช้กับมันกับทุกรายการของแดงอยู่
แก้ไข:
หลังจากการดีบั๊กหน่อยนะฉันรู้ว่าตอนที่การตั้งค่า SelectedThing
ขึ้นรถโหลด, SelectedItem
ซากศพ null
.
แก้ไข:
ที่นี่คือ OnLoaded
วิธีการอยู่ใน ViewModel
อยู่ที่ไหนผมเป็นการตั้งค่า SelectedThing
ถ้าอผู้ใช้ที่เลือกไว้มันในขณะที่ความเดิมตอนที่แล้วโดยใช้โปรแกร. จุดประสงค์คือการเก็บส่วนที่เลือกไว้หลังร้านปิดและเปิดร้านใหม่ที่ app
public IAsyncRelayCommand OnLoadedCommand { get; set; }
ใน constructor:
OnLoadedCommand = new AsyncRelayCommand(OnLoaded);
ในมุมมอง:
<b:Interaction.Triggers>
<b:EventTrigger EventName="Loaded">
<b:InvokeCommandAction Command="{Binding OnLoadedCommand}" />
</b:EventTrigger>
</b:Interaction.Triggers>
ที่จริงวิธีการ:
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;
}
}