如何在同一ContentView中使用(Populate / item.source)2个ListViews和2个不同的BindingContext

时间:2019-03-22 21:15:28

标签: c# xamarin data-binding binding

我正在尝试从不同的ViewModel和不同的模型填充2个列表视图。

我尝试在2个绑定上下文之间使用Itemsource。 (请参阅我的view.cs)

我尝试在我的视图中使用一个名称,然后在[xamarin论坛]中将源作为示例发送。1

我基本尝试在绑定中使用Source = {x:Reference Model.Protocol}

任何人工作

我的看法是: XAML

<?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="H2XA.View.ConnectView"
             x:Name="Root">
<!--I put a name where but i don't know if I can cuz i use Detail=new ConnectView every time -->
    <ContentPage.Content >
        <Grid >
            <!-- Código principal-->
            <ScrollView>
                <StackLayout  VerticalOptions="Start" >
                    <!--Exame -->
                    <Button x:Name="ConfigExam"  
                            Text="Características de exame" 
                            Clicked="ConfigExam_Clicked"
                            BackgroundColor="#FFFFFFFF"/>
                    <StackLayout x:Name="AllConfigExam"  VerticalOptions="Fill" HorizontalOptions="CenterAndExpand"  >
                        <Button x:Name = "NewProtocol"
                                Text="Criar novo protocolo" 
                                Clicked="NewProtocol_Clicked"
                                HorizontalOptions="Center"/>
                        <BoxView />
                        <StackLayout x:Name="ProtoScreen" VerticalOptions="Start" >
                             <ListView x:Name="Protocol_Disponivel"  ItemSelected="OnSelectionP" IsPullToRefreshEnabled="True" >
                                <ListView.ItemTemplate>
                                    <DataTemplate>
                                        <ViewCell>
                                            <ViewCell.ContextActions>
                                                <MenuItem Text="Editar" CommandParameter="{Binding .}"
                                                          Clicked="EditarProtocol_Clicked" />
                                                <MenuItem Text="Remover" CommandParameter="{Binding .}"
                                                          Clicked="RemoverProtocol_Clicked" />
                                            </ViewCell.ContextActions>
                                            <StackLayout Padding="5,0,5,0">
                                                <Label Text="Intervalos de tempo:" />
                                                <StackLayout Orientation="Horizontal">
                                                    <Label Text="0 | "/>
                                                    <Label Text="{Binding Model.Patient.intervaldescription,Source={x:Reference Root}}" Font="14" />
                                                </StackLayout>
                                            </StackLayout>
                                        </ViewCell>
                                    </DataTemplate>
                                </ListView.ItemTemplate>
                            </ListView>
                        </StackLayout>
                    </StackLayout>
                    <!--Conexão -->
                    <Button x:Name="ConfigConn"  
                            Text="Aparelhos" 
                            Clicked="ConfigConn_Clicked"
                            BackgroundColor="#FFFFFFFF"/>
                    <StackLayout x:Name="AllConfigConn"  VerticalOptions="Fill" HorizontalOptions="CenterAndExpand" >

                        <StackLayout  Orientation="Horizontal"  HorizontalOptions="Center" >

                            <StackLayout Padding="10,10,10,10" VerticalOptions="Start">
                                <Button x:Name="connection"  
                                         Text="Procurar bluetooth" 
                                         Clicked="connection_Clicked"
                                         HorizontalOptions="Center"/>
                                <Label x:Name="Status_recebimento_N" 
                                        Text="Status"
                                                                                    HorizontalOptions="Center"/>
                                <Label x:Name="Status_recebimento" 
                                        Text="{Binding Connectionwaymsg,Mode=Default}"
                                                                                    HorizontalOptions="Center"/>
                            </StackLayout>
                        </StackLayout>
                        <StackLayout x:Name="ConnScreen" VerticalOptions="Start">
                            <Label x:Name="MAC_title" 
                                    Text="MAC do aparelho"
                                    VerticalOptions="Center" 
                                    HorizontalOptions="Center"/>
                            <ListView x:Name="MACS_Disponiveis"  ItemSelected="OnSelectionD" IsPullToRefreshEnabled="True" >
                                <ListView.ItemTemplate>
                                    <DataTemplate>
                                        <ViewCell>
                                            <ViewCell.ContextActions>
                                                <MenuItem Text="Renomear" CommandParameter="{Binding .}"
                                                          Clicked="ReplaceMAC_Clicked" />
                                                <MenuItem Text="Remover" CommandParameter="{Binding .}"
                                                          Clicked="RemoveMAC_Clicked" />
                                            </ViewCell.ContextActions>
                                            <StackLayout Padding="5,0,5,0">
                                                <Label Text="MAC:" />
                                                <Label Text="{Binding .}" Font="14" />
                                            </StackLayout>
                                        </ViewCell>
                                    </DataTemplate>
                                </ListView.ItemTemplate>
                            </ListView>
                        </StackLayout>
                    </StackLayout>
                </StackLayout>
            </ScrollView>
            <!-- Voltar-->
            <StackLayout HorizontalOptions ="End" VerticalOptions ="End" Padding="30">
                <Button x:Name="Backcon"  Style="{StaticResource BackButton}"                     
                        Text="Voltar"  Clicked="Backcon_Clicked" />
            </StackLayout>
        </Grid>
    </ContentPage.Content>
</ContentPage>

.CS

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ConnectView : ContentPage
{
    public IConnections Conectado;

    public ConnectView ()
    {
      InitializeComponent ();

        Conectado = DependencyService.Get<IConnections>();
        BindingContext = App.CVM;
        MACS_Disponiveis.ItemsSource = App.CVM.BLE_Devices;
//I tried where uses 2 times but didn't work too
        //BindingContext = App.SVM;
        Protocol_Disponivel.ItemsSource = App.SVM.Saved_Protocols;

        if (App.SVM.Saved_Protocols.Count > 0)
            ProtoScreen.IsVisible = true;

        Status_recebimento.MaxLines=1;
    }
    #region Protocol


    private void NewProtocol_Clicked(object sender, EventArgs e)
    {
        App.MDP.Detail = new SetupView();
    }

    #endregion

    #region Aparelhos e MACs


    private async void OnSelectionD(object sender, SelectedItemChangedEventArgs e)
    {
        if (e.SelectedItem == null)
        {
            return;
        }
        await DisplayAlert("Selecionado", e.SelectedItem.ToString(), "Ok");
        string a = e.SelectedItem.ToString().Substring(0, 12);

    }

    private void RenomearMAC_Clicked(object sender, EventArgs e)
    {
        var item = (MenuItem)sender;
        App.CVM.BLE_Devices.Remove(item.CommandParameter.ToString());
    }

    private void RemoverMAC_Clicked(object sender, EventArgs e)
    {
        var item = (MenuItem)sender;
        App.CVM.BLE_Devices.Remove(item.CommandParameter.ToString());
    }


    #endregion

    private void Backcon_Clicked(object sender, EventArgs e)
    {

        App.MDP.Detail = new StarterView();
    }
}

}

我的视图模型是:

public class ConnectViewModel : INotifyPropertyChanged
{
    #region Variables
    public NewStatusCMD newStatusCMD { get; }
    public IConnections All_conn;
    public Connection Bl_Conn;
    private string conectionwaymsg;
    public string bluetoothstatus;
    public string mldplink;
    public string MLDPINBUFF;

    //BLE_Devices is my List there
    public ObservableCollection<string> BLE_Devices;
    public event PropertyChangedEventHandler PropertyChanged;
    #endregion

    public ConnectViewModel()
    {
        Bl_Conn = new Connection();

        BLE_Devices = new ObservableCollection<string>();

    }

    public string Connectionwaymsg
    {
        get { return conectionwaymsg; }
        set
        {
            conectionwaymsg = value;
            OnPropertyChanged(); // Realize the event after the new value is informed for adapted.
        }

    }

    public string Mldplink
    {
        get { return mldplink; }
        set
        {
            mldplink = value;
            OnPropertyChanged(); // Realize the event after the new value is informed for adapted.
        }

    }
   //Padrão Default
    private void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

        if (Mldplink != null)
        {
            MLDPINBUFF = MLDPINBUFF + mldplink;
            mldplink = null;
        }
    }

    private void FillListView()
    {
        var a = All_conn.getMAC();
        for ( int i=0; i < a.Count; i++)  BLE_Devices.Add(a[i]); 
    }

    private void Activation_Clicked(object sender, EventArgs e)
    {
        All_conn.ConnectBluetooth();
    }
    private void connection_Clicked(object sender, EventArgs e)
    {
        All_conn.ConnectBluetooth();
    }

    }
}

    public class SetupViewModel : INotifyPropertyChanged
    {

        public Protocol Protocol_Model;
        public List<Protocol> Saved_Protocols;
        public int[] modelinterval;
        public SetupViewModel()
        {
            modelinterval = new int[16] { 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 };
            Protocol_Model = new Protocol(modelinterval);
            Saved_Protocols = new List<Protocol>();


        }

        public event PropertyChangedEventHandler PropertyChanged;

    }
}

我的模特是:

public class Connection: INotifyPropertyChanged
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public string MAC { get; set; }
        private string bluetoothStatus;//private pra não confundir o uso ...
        public string BluetoothStatus
        {
            get { return bluetoothStatus; }
            set
            {
                bluetoothStatus = value;
                App.CVM.newStatusCMD.StatusCanExecuteChanged();
            }
        }

        private bool _connvisible;
        public bool ConnVisible
        {
            get { return _connvisible; }
            set
            {
                _connvisible = value;
                OnPropertyChanged();

            }
        }

        public Connection()
        {
            List<char> Testee;
        }

        public event PropertyChangedEventHandler PropertyChanged;

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

    }

public class Protocol
{
    public string Name;
//This is the variable that i tried to use
    public string intervaldescription;
    public int total_Time;
    public string interval_Time;
    public int[] example;
    public int[] intervalBS;

    public Protocol( int[] interval)
    {
        intervalBS = interval;
        intervaldescription = Interval_line(interval);
    }

    private string Interval_line(int[] interval)
    {
        int i;
        string inter_string="";

        return inter_string;
    }
}

我没有使用像cross或lite这样的通用MVVM,因为我的老板使用了一个类似的地雷。

任何帮助

预先感谢

吉尔赫姆

1 个答案:

答案 0 :(得分:0)

问题很简单,要使用notify属性或绑定,您需要将变量设置为属性。 为此,您需要在模型中添加{get; set;}方法,因为绑定是通过链接器/执行器来完成的。

在那种情况下,最严重的问题是在协议类中,因为字符串inervaldescription没有属性方法{设置;}

public class Protocol
{
    public string Name;
    //This is the variable that i tried to use -> IT'S NOT A VARIABLE
    public string intervaldescription{ get; set;}
    public int total_Time;
    public string interval_Time;
    public int[] example;
    public int[] intervalBS;

    public Protocol( int[] interval)
    {
        intervalBS = interval;
        intervaldescription = Interval_line(interval);
    }

    private string Interval_line(int[] interval)
    {
        int i;
        string inter_string="";

        return inter_string;
    }
}

正如杰森(Jason)所说的那样,这段代码有点混乱,因此我需要删除stacklayouts并将几乎所有代码都设置为gridlayout.I不知道一种删除scrowview的方法,但其他结构也可以工作。

这里需要提供的其他信息是Jason给我的关于绑定上下文与Itemsource的信息。

当我使用物品来源时,我不需要对该结构使用绑定上下文。所以我可以使用列表/集合,只是注意到谁是我的来源。

public partial class ConnectView : ContentPage
{
    public IConnections Conectado;

    public ConnectView ()
    {
      InitializeComponent ();

        Conectado = DependencyService.Get<IConnections>();
        BindingContext = App.CVM;
        MACS_Disponiveis.ItemsSource = App.CVM.BLE_Devices;
        Protocol_Disponivel.ItemsSource = App.SVM.Saved_Protocols;

        if (App.SVM.Saved_Protocols.Count > 0)
            ProtoScreen.IsVisible = true;

        Status_recebimento.MaxLines=1;
    }
//.
//.
//.
}

谢谢杰森(Jason)给出的解释:)

致谢

吉尔赫姆