Search code examples
avaloniauiavalonia

How to bind properties for a custom user control properly in avalonia ui


I am trying to display a text on a custome user control. I want that text to be passed via a mainview this is the code I have: MainView.axaml

<cc:Slot Grid.Row="0" Grid.Column="1" Dot="Number one"/>
<cc:Slot Grid.Row="0" Grid.Column="2" Dot="Number two"/>

This is my custom user control: Slot.axaml

<UserControl 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:controls="clr-namespace:Avalonia.Controls;assembly=Avalonia.Controls"
             mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
             xmlns:cc="clr-namespace:Diagnostica.CustomControls;assembly=Diagnostica.CustomControls"
             x:Class="Diagnostica.CustomControls.OmniSlot">
<Button>
      <TextBlock Text="{Binding Dot}"/>
</Button>
    </Grid>
  </Button>
</UserControl>

and its .cs file"

Slot.axaml.cs

        public string Dot
        {
            get => GetValue(DotProperty);
            set => SetValue(DotProperty, value);
        }

        public static readonly StyledProperty<string> DotProperty =
                AvaloniaProperty.Register<Slot, string>(nameof(Dot), defaultValue: "Black");

what i get like this is a disabled box. How can this get fixed?


Solution

  • View:

    <Rectangle Stroke="{TemplateBinding DotColor}" StrokeThickness="2" Width="20" Height="20" Fill="{TemplateBinding DotColorBrush}" VerticalAlignment="Top" HorizontalAlignment="Right"/>
    

    ViewModel:

        public static readonly StyledProperty<string> DotColorProperty = AvaloniaProperty.Register<OmniSlotControl, string>(nameof(DotColor), "Red");
    
        public string DotColor
        {
            get => GetValue(DotColorProperty);
            set
            {
                SetValue(DotColorProperty, value);
                DotColorBrush = Avalonia.Media.Brush.Parse(value);
            }
        }