无论如何我可以将两个值绑定到我的XAML中吗?

问题描述 投票:2回答:5

我有一个listview,我将从数据库中获取的值绑定到我的XAML。我现在将一个值绑定到我的XAML中,但我希望绑定两个值,是可能还是只能在代码中?如果是这样,我将如何实现这一目标。

这是我的代码:

    public class items
    {
        public string infoOne { get; set;}
        public string infoTwo { get; set;}
    }

    async void loadList ()
    {

        var getItems = await phpApi.getEvents ();


        theList = new List <items> ();
        foreach (var currentitem in getItems["results"]) {

            theList.Add (new items () {

                infoOne = currentitem ["name"].ToString (), 
                infoTwo = currentitem ["phone"].ToString ()
            });

       mylist.ItemsSource = theList;

     }

XAML:

        <Label Text = "{Binding infoOne}" /> //How could I add infoTwo to the same label and also add a space between them?
c# xamarin xamarin.forms
5个回答
5
投票

不幸的是,这不是(还是?)支持。正如Pheonys所说,你可以在WPF中执行此操作,但不能在Xamarin.Forms中执行此操作。

如果要绑定到一个ViewModel中的两个属性,则应创建另一个属性,如下所示:

public class items
{
    public string infoOne { get; set;}
    public string infoTwo { get; set;}
    public string infoFull
    {
        get { return $"{infoOne} {infoTwo}"; }
    }
}

只需将您的项目类更改为此。

你的XAML将是这样的:

<Label Text = "{Binding infoFull}" />

0
投票

做一些假设(因为我没有在Xamarin中玩过),在WPF XAML中你可以使用多绑定类和字符串格式化程序。

MultiBinding Class (MSDN)

这样做的一个例子可以在这个堆栈溢出问题的答案中找到:How to bind multiple values to a single WPF TextBlock?


0
投票

您可以添加get-only属性并绑定到该属性。

public string combinedInfo { get; } = $"{infoOne} {infoTwo}";


0
投票

没有内置的MultiBinding支持,但您可以使用Xamarin.Forms.Proxy库来实现它。

    <Label.Text>
      <xfProxy:MultiBinding StringFormat="Good evening {0}. You are needed in the {1}">
        <Binding Path="User" />
        <Binding Path="Location" />
      </xfProxy:MultiBinding>
    </Label.Text>

0
投票

你试过以下吗?

public class items
{
    public string infoOne { get; set;}
    public string infoTwo { get; set;}
    public string infoOneAndinfoTwo {get; set;}
}

async void loadList ()
{

    var getItems = await phpApi.getEvents ();


    theList = new List <items> ();
    foreach (var currentitem in getItems["results"]) {

        theList.Add (new items () {

            infoOne = currentitem ["name"].ToString (), 
            infoTwo = currentitem ["phone"].ToString (),
            infoOneAndinfoTwo = infoOne + " " + infoTwo
        });

   mylist.ItemsSource = theList;

 }

XAML:

<Label Text = "{Binding infoOneAndinfoTwo}" /> 
© www.soinside.com 2019 - 2024. All rights reserved.