Avalonia FuncValueConverter的使用

public static class ConverterUtilsConv
{
    public static FuncValueConverter<bool, bool> ReverseBool { get; } = new((arg => !arg));

    public static FuncValueConverter<int, int, bool> GreaterInt { get; } = new((arg1, arg2) => arg1 > arg2);

    public static FuncValueConverter<long, long, bool> GreaterLong { get; } = new((arg1, arg2) => arg1 > arg2);

    public static FuncValueConverter<double, double, bool> GreaterDouble { get; } = new((arg1, arg2) => arg1 > arg2);

    public static FuncValueConverter<decimal, decimal, bool> GreaterDecimal { get; } = new((arg1, arg2) => arg1 > arg2);


    public static FuncValueConverter<bool, string> GetDeviceOnlineSvgPath { get; } = new((arg =>
    {
        if (arg)
        {
            return "avares://xxx.Resources/Assets/Common/Online_icon.svg";
        }

        return "avares://xxx.Resources/Assets/Common/Offline_icon.svg";
    }));

   public static FuncValueConverter<bool, IBrush> GetDeviceOnlineTextForeground { get; } = new((arg =>
    {
        if (arg)
        {
            return Brush.Parse("#18b633");
        }

        return Brush.Parse("#a8a8a8");
    }));
<UserControl xmlns="https://github.com/avaloniaui"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:converters="clr-namespace:xxx.Converters">
    <StackPanel>
        <!-- 使用 ReverseBool 转换器 -->
        <Button Content="反转状态按钮"
                IsEnabled="{Binding SomeBoolValue, 
                           Converter={x:Static converters:ConverterUtilsConv.ReverseBool}}" />

        <!-- 使用 GetDeviceOnlineSvgPath 转换器 -->
        <Image Width="16" Height="16">
            <Image.Source>
                <Binding Path="IsDeviceOnline" 
                         Converter="{x:Static converters:ConverterUtilsConv.GetDeviceOnlineSvgPath}">
                    <!-- 如果SVG需要Svg.Skia等进行加载,可能需要进一步的转换,此处绑定结果为路径字符串 -->
                </Binding>
            </Image.Source>
        </Image>
    </StackPanel>
</UserControl>
posted @ 2026-01-30 16:23  Timskt  阅读(4)  评论(0)    收藏  举报