John Livermore
John Livermore

Reputation: 31313

Xamarin Forms - c# equivalent of XAML bindings

I want to convert the following XAML to instead use a custom ViewCell defined in C#...

<ListView x:Name="___listview" HasUnevenRows="True">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout>
                    <Button Image="{Binding ImageName}" Command="{Binding ShowDetailsCommand}" />
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

So after converting I have...

<ListView x:Name="___listview" HasUnevenRows="True">
    <ListView.ItemTemplate>
    </ListView.ItemTemplate>
</ListView>

and the C#...

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
        ___listview.ItemsSource = Repository.GetList();
        ___listview.ItemTemplate = new DataTemplate(typeof(CustomViewCell));
    }
}

public class CustomViewCell : ViewCell
{
    bool _initialized = false;

    public CustomViewCell()
    {
        var stack = new StackLayout();

        var button = new Button();

        stack.Children.Add(button);

        View = stack;
    }
}

What is the code to needed complete the binding syntax on the Button's Image and Command properties as has been done in the XAML?

Upvotes: 1

Views: 126

Answers (1)

Jason
Jason

Reputation: 89102

var button = new Button();
button.SetBinding(Button.ImageProperty, new Binding("ImageName"));
button.SetBinding(Button.CommandProperty, new Binding("ShowDetailsCommand"));

Upvotes: 5

Related Questions