例子也绑定了自定义类,系统类同理,目前Avalonia不支持绑定结构。

BindToFont.axaml代码

<Window xmlns="https://github.com/avaloniaui"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:local ="using:AvaloniaUI"
         xmlns:sys="clr-namespace:System;assembly=mscorlib"
        Height="300" Width="300"
        x:Class="AvaloniaUI.BindToFont"
        Title="BindToFont">
    <!--https://docs.avaloniaui.net/docs/concepts/markupextensions-->
    <Window.Resources>
        <FontFamily x:Key="CustomFont">Calibri</FontFamily>
    </Window.Resources>
    <StackPanel Margin="10" >
        <TextBlock Margin="5" Text="{x:Static Member=local:BindToFont.MyGuid}"></TextBlock>
        <TextBox Name="input" >Hello Avalonia</TextBox>
        <TextBlock Margin="5" Text="{local:BindableMe {Binding #input.Text}}"></TextBlock>
        <TextBlock Margin="5" Text="{Binding Source={StaticResource CustomFont}, Path=Name}"></TextBlock>
    </StackPanel>
</Window>

BindToFont.axaml.cs代码

using Avalonia;
using Avalonia.Controls;
using Avalonia.Data;
using Avalonia.Data.Converters;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using CommunityToolkit.Mvvm.ComponentModel;
using System;
using System.Linq;

namespace AvaloniaUI;
public class BindableMe
{
    private readonly BindingBase first;
    public BindableMe(BindingBase first)
    {
        this.first = first;
    }
    public object ProvideValue(IServiceProvider serviceProvider)
    {
        /*
        var target = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget))!;
        var targetProperty = target.TargetProperty as AvaloniaProperty;
        var targetType = targetProperty?.PropertyType;
        */
        var mb = new MultiBinding()
        {
            Bindings = new[] { first },
            Converter = new FuncMultiValueConverter<string, string>(s => $"Total Bindings: {s.Count()}, Text: " + s.ElementAt(0))
        };

        return mb;
    }
}
public partial class BindToFont : Window
{
    public static string? MyGuid
    {
        get; set;
    } = Guid.NewGuid().ToString();

    public BindToFont()
    {
        InitializeComponent();
    }
}

运行效果

image

 

posted on 2025-08-05 12:50  dalgleish  阅读(12)  评论(0)    收藏  举报