Skip to content

Commit cf20497

Browse files
committed
feat: add EnumToDescription converter.
1 parent 4ce9ada commit cf20497

File tree

3 files changed

+35
-4
lines changed

3 files changed

+35
-4
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
using System;
2+
using System.ComponentModel;
3+
using System.Reflection;
4+
using Avalonia.Data.Converters;
5+
6+
namespace Client.Avalonia.Converters;
7+
8+
public static class EnumConverter
9+
{
10+
public static readonly IValueConverter EnumToDescriptionConverter =
11+
new FuncValueConverter<object?, string>(obj =>
12+
{
13+
if (obj is not Enum value)
14+
return string.Empty;
15+
16+
var field = value.GetType().GetField(value.ToString());
17+
var attribute = field?.GetCustomAttribute<DescriptionAttribute>();
18+
return attribute?.Description ?? value.ToString();
19+
});
20+
}

src/Client.Avalonia/ViewModels/MainWindowViewModel.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -146,8 +146,8 @@ [ObservableProperty] [Description("进度百分比")]
146146
[Flags]
147147
public enum DownloadStatus
148148
{
149-
NotStarted,
150-
Downloading,
151-
Paused,
152-
Completed
149+
[Description("未开始")] NotStarted,
150+
[Description("下载中")] Downloading,
151+
[Description("已暂停")] Paused,
152+
[Description("已完成")] Completed
153153
}

src/Client.Avalonia/Views/MainWindow.axaml

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
55
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
66
xmlns:converters="clr-namespace:Avalonia.Controls.Converters;assembly=Avalonia.Controls"
7+
xmlns:cvt="clr-namespace:Client.Avalonia.Converters"
78
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
89
x:Class="Client.Avalonia.Views.MainWindow"
910
x:DataType="vm:MainWindowViewModel"
@@ -47,6 +48,7 @@
4748
<SelectableTextBlock
4849
HorizontalAlignment="Left"
4950
Text="{Binding Statistics.Speed, StringFormat='下载速度:{0:F2} MB/s'}" />
51+
5052
<SelectableTextBlock
5153
HorizontalAlignment="Center">
5254
<Run Text="已下载:" />
@@ -57,9 +59,18 @@
5759
</SelectableTextBlock>
5860

5961
<SelectableTextBlock
62+
Name="RemainingTimeTextBlock"
6063
HorizontalAlignment="Right"
64+
IsVisible="{Binding Status,
65+
Converter={StaticResource EnumToBooleanConverter},
66+
ConverterParameter={x:Static vm:DownloadStatus.Downloading}}"
6167
Text="{Binding Statistics.Remaining, StringFormat='剩余时间:{0:mm\\:ss}'}" />
68+
<SelectableTextBlock
69+
HorizontalAlignment="Right"
70+
IsVisible="{Binding !#RemainingTimeTextBlock.IsVisible}"
71+
Text="{Binding Status,Converter={x:Static cvt:EnumConverter.EnumToDescriptionConverter}}" />
6272
</Panel>
73+
6374
<ProgressBar
6475
Name="Bar"
6576
ShowProgressText="True"

0 commit comments

Comments
 (0)