2017-08-18 85 views
1

说我有一个只读的模式...Xamarin MVVM自定义模型属性?

[DataContract] 
public partial class Person { 
    [DataMember] 
    public virtual string LastName { get; set; } 

    [DataMember] 
    public virtual string FirstName { get; set; } 
} 

的视角...

<?xml version="1.0" encoding="UTF-8"?> 
<ContentPage 
    xmlns="http://xamarin.com/schemas/2014/forms" 
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
    x:Class="TheApp.APage" 
    BackgroundColor="#03264A" 
    Padding="0,0,0,0"> 
    <ContentPage.Content> 
     <StackLayout 
      BackgroundColor="Transparent"> 
      <ListView 
       ItemsSource="{Binding PersonSearchCollection}"> 
       <ListView.ItemTemplate> 
        <DataTemplate> 
         <ViewCell> 
          <Label 
           Text="{Binding FirstName}" /> 
         </ViewCell> 
        </DataTemplate> 
       </ListView.ItemTemplate> 
      </ListView> 
     </StackLayout> 
    </ContentPage.Content> 
</ContentPage> 

而一个视图模型(基本思路)

namespace TheApp.ViewModels { 
    public class APagePageViewModel : Helpers.BindableBase { 

     private ObservableCollection<Person> _PersonSearchCollection = new RangeObservableCollection<Person>(); 

     public ObservableCollection<Person> PersonSearchCollection { 
      get { return _PersonSearchCollection; } 
      set { SetProperty(ref _PersonSearchCollection, value); } 
     } 
    } 
} 

我的ListView控件绑定到一个类型为Person的ObservableCollection。当用户输入要搜索的名称时,这会从ServiceStack调用中填充。

目前DataTemplate中的标签绑定到名字,但我希望它是一个新的属性:FullName(Person.FirstName +“”+ Person.LastName)。

我该如何将属性添加到我无法编辑的模型?我是否需要为模型本身使用单独的VM,并将ObservableCollection更改为该类型?任何例子都会很棒!

对不起,如果这是一个基本的问题,我对Xamarin相当陌生。

谢谢!

+0

更改数据模板 <标签文本=“{结合姓} “ Ramankingdom

回答

1

更改您的视图细胞

<ViewCell> 
<StackLayout Orientation="Horizontal"> 
    <Label Text="{Binding FirstName}" 
    <Label Text=" " 
    <Label Text="{Binding LastName}" 
</StackLayout> 
</ViewCell> 

其他方式

  1. 定义一个自定义对象

    public class CustomPerson 
        { 
         public CustomPerson(Person P) 
         { 
          FirstName = P.FirstName; 
          LastName = P.LastName; 
         } 
         public string FirstName { get; set; } 
         public string LastName { get; set; } 
         public string FullName 
         { 
          get { return string.Format("{0} {1}", FirstName, LastName);} 
         } 
    
        } 
    

(2)定义一个集合吸气剂

public IEnumerable<CustomPerson> CustomCollection 
{ 
    get { return _personSearchCollection.Select(p => new CustomPerson(p)); } 
} 

当你更新个人搜索集合筹集定义集合性质的变化。

  • 最后与CustomCollection的
  • 绑定
    +0

    谢谢你的回应。我可以看到这是如何工作的,但它似乎不是最好的方式呢?我觉得只是为了空间,角色等等而制作一个标签是矫枉过正的?例如,如果我想制作:John Smith(19)我需要7个标签? 3为FirstName/LastName/Age,4为2空格和2个括号。 – ksumarine

    +0

    我是新来的xamarin,但我可以使它在wpf xaml单行中工作。我不知道是否有Xamarin – Ramankingdom

    +0

    这里运行的关键。我不知道你将如何使用它https://developer.xamarin。com/guides/xamarin-forms /用户界面/文本/标签/#Formatted_Text – Ramankingdom