Xamarin Forms - 相当于XAML绑定的c#

时间:2017-01-16 21:46:38

标签: xamarin xamarin.forms

我想将以下XAML转换为使用在C#中定义的自定义ViewCell ...

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

转换后我有......

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

和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;
    }
}

在XAML中完成按钮的ImageCommand属性上需要完成绑定语法的代码是什么?

1 个答案:

答案 0 :(得分:4)

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