首页 > 解决方案 > 单个标签可以显示 2 个数据字段,由用户交替选择

问题描述

我正在尝试使用单个标签在 Xamarin 表单中交替显示两个数据字段之一。只有标签 1 显示绑定字段和我尝试使用变量“DisplayField”的第二个标签未显示“Contact_Address”或“Contact_eMail”

模型类

public class Contacts
{
    [PrimaryKey][Autoincrement]
    public int Contact_ID { get; set; }
    public string Contact_Name { get; set; }
    public string Contact_Address { get; set; }
    public string Contact_eMail { get; set; }
    public string DisplayField { get; set; }
}

XAML 页面

  <StackLayout>
        <Button Text="Display Address" FontSize="Large" HorizontalOptions="Center" VerticalOptions="Fill" Clicked="Display_Address" />
        <Button Text="Display Email" FontSize="Large" HorizontalOptions="Center" VerticalOptions="Fill" Clicked="Display_eMail" />
        <Entry HorizontalOptions="FillAndExpand" Text="{Binding DisplayField}" />
        <ListView x:Name="listView" HasUnevenRows="True" >
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell >
                        <StackLayout Orientation="Vertical" VerticalOptions="CenterAndExpand" >
                            <Frame >
                                <StackLayout Orientation="Vertical" VerticalOptions="Center">
                                    <Label Text="{Binding Contact_Name}" FontSize="Medium" LineBreakMode="WordWrap" />
                                    <Label Text="{Binding DisplayField}" LineBreakMode="WordWrap" />
                                </StackLayout>
                            </Frame>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>

背后的代码

public partial class FieldSwap : ContentPage
{
    readonly FieldViewModel _fieldViewModel;
    readonly SQLiteAsyncConnection _connection = DependencyService.Get<ISQLite>().GetConnection();
    public ObservableCollection<Contacts> CList { get; set; }
    public static string DisplayField { get; private set; }

    public static int caseSwitch { get; private set; }

    public FieldSwap()
    {
        InitializeComponent();
        _fieldViewModel = new FieldViewModel();
        _fieldViewModel.Field = "Contact_Address";
        
        this.BindingContext = _fieldViewModel;
    }

    public static void SelectField()
    {
        

        switch (caseSwitch)
        {
            case 1:
                DisplayField = "Contact_Address";
                break;

            case 2:
                DisplayField = "Contact_eMail";
                break;

            default:
                DisplayField = ("Contact_Address");
                break;
        }
    }

    private void Display_Address(object sender, EventArgs e)
    {
        caseSwitch = 1;
        SelectField();
        ReadData();
    }

    private void Display_eMail(object sender, EventArgs e)
    {
        caseSwitch = 2;
        SelectField();
        ReadData();
    }

    public void ReadData()
    {
        var list = _connection.Table<Contacts>().ToListAsync().Result;
        CList = new ObservableCollection<Contacts>(list);
        listView.ItemsSource = CList;
    }
}

查看模型类

public class FieldViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    String _field;

    public string Field
    {
        set
        {
            if (!value.Equals(_field, StringComparison.Ordinal))
            {
                _field = value;
                OnPropertyChanged("DisplayField");
            }
        }
        get
        {
            return _field;
        }
    }

    void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new 
        PropertyChangedEventArgs(propertyName));
    }
}

屏幕截图 屏幕截图 2

标签: sqlitexamarin.formslabelinotifypropertychanged

解决方案


如果您想通过用户选择在 ListView 中显示不同的值,我建议您可以使用 Picker 进行选择,我做了一个示例,您可以看看。

 <ContentPage.Content>
    <StackLayout>
        <Picker x:Name="choose" SelectedIndexChanged="choose_SelectedIndexChanged">
            <Picker.ItemsSource>
                <x:Array Type="{x:Type x:String}">
                    <x:String>Contact_Address</x:String>
                    <x:String>Contact_eMail</x:String>
                </x:Array>
            </Picker.ItemsSource>
        </Picker>
        <ListView
            x:Name="listview1"
            HasUnevenRows="True"
            ItemsSource="{Binding items}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Orientation="Vertical" VerticalOptions="Center">
                            <Label
                                FontSize="Medium"
                                LineBreakMode="WordWrap"
                                Text="{Binding Contact_Name}" />
                            <Label
                                IsVisible="{Binding Source={x:Reference root}, Path=BindingContext.selectedm}"
                                LineBreakMode="WordWrap"
                                Text="{Binding Contact_eMail}" />
                            <Label
                                IsVisible="{Binding Source={x:Reference root}, Path=BindingContext.selecteda}"
                                LineBreakMode="WordWrap"
                                Text="{Binding Contact_Address}" />
                        </StackLayout>


                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
</ContentPage.Content>

 public partial class Page31 : ContentPage, INotifyPropertyChanged
{
    public ObservableCollection<Contacts> items { get; set; }
    private Boolean _selecteda;
    public Boolean selecteda
    {
        get { return _selecteda; }
        set
        {
            _selecteda = value;
            RaisePropertyChanged("selecteda");
        }
    }
    private Boolean _selectedm;
    public Boolean selectedm
    {
        get { return _selectedm; }
        set
        {
            _selectedm = value;
            RaisePropertyChanged("selectedm");
        }
    }
    public Page31()
    {
        InitializeComponent();

        items = new ObservableCollection<Contacts>();

        for(int i=0;i<20;i++)
        {
            Contacts contact = new Contacts()
            {
                Contact_ID = i, Contact_Name = "cherry " + i, Contact_Address = "the street " + i, Contact_eMail = "cherry@outlook.com "+i
            };
            items.Add(contact);
        }
       
        this.BindingContext = this;
       
    }
  
    public event PropertyChangedEventHandler PropertyChanged;   
    public void RaisePropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    private void choose_SelectedIndexChanged(object sender, EventArgs e)
    {
        var picker = (Picker)sender;
        int selectedIndex = picker.SelectedIndex;

        if (selectedIndex ==0)
        {
            selecteda = true;
            selectedm = false;
        }
        else
        {
            selectedm = true;
            selecteda = false;
        }
    }
}

在此处输入图像描述


推荐阅读