Search code examples
c#wpfxamlavalonia

Binding a property obtained from a method, that returns object


I have a problem with binding with a XAML file. There is a DataContext of Template class that has a GetDisplayParams() method. Method GetDisplayParams() returns an object of type TemplateDisplayParams, that has a Width property. I just need to bind TextBox to this property, but nothing works for me.

.xaml:

<TextBox Text="{Binding GetDisplayParams.Width}"/> 

.axaml.cs:

public TemplateCompositeAttributesSettingsView(Scripting.Template dataContext) : this()
{
    DataContext = dataContext;
    Console.WriteLine( ((Scripting.Template)DataContext).GetDisplayParams().Width ); // return int.
}

Error: enter image description here


Solution

  • As @BionicCode said, in WPF and I think Avalonia in XAML can't bind to methods. Therefore, I had to create a TemplateCompositeAttributesSettingsViewModel and specify a public property there and later bind the DataContext TextBox to this ViewModel.

    .xaml

    <StackPanel Name="MinWidthMinHeightStackPanel" Margin="3.5" Orientation="Horizontal">
                <!--TODO-->
                <TextBox Text="{Binding MinWidth}"/> 
                <TextBlock Margin="20,0,20,0" Text="x" VerticalAlignment="Center"/>
                <!--TODO-->
                <TextBox Text="{Binding MinHeight}"/>
    </StackPanel>
    

    TemplateCompositeAttributesSettingsView.cs:

    public TemplateCompositeAttributesSettingsView(Scripting.Template dataContext) : this()
    {
        DataContext = dataContext;
        var templateCompositeAttributesSettingsViewModel = new TemplateCompositeAttributesSettingsViewModel( dataContext );
        this.FindControl<StackPanel>( "MinWidthMinHeightStackPanel" ).DataContext = templateCompositeAttributesSettingsViewModel;
    }
    

    TemplateCompositeAttributesSettingsViewModel.cs:

    class TemplateCompositeAttributesSettingsViewModel : ViewModelBase
    {
        public TemplateCompositeAttributesSettingsViewModel(Scripting.Template DataContext)
        {
            this.DataContext = DataContext;
        }
    
        public int MinWidth
        {
            get => DataContext.GetDisplayParams().Width;
        }
    
        public int MinHeight
        {
            get => DataContext.GetDisplayParams().Height;
        }
    
        public Scripting.Template DataContext { get; set; }
    }
    

    Output: enter image description here