Кнопка Команда не находит Binded ViewModel с помощью rg.plugin.popup - PullRequest
0 голосов
/ 01 ноября 2019

проблема возникает при попытке привязать свойства представления к любому источнику, созданному в ViewModel, например, тест свойства текста <-binding-> метки (ниже по коду) не работает, но свойство текста кнопки, которую я создаюпривязка к другому объекту, переданному в эту viewModel, и работает нормально. Я просто хотел бы понять, почему Binding не работает как обычно. Вот код.

XAML.cs

public PopupView(Func<bool> metodo, Tarefa tarefa)
{
    BindingContext = new ViewModels.Popups.PopupViewModel(metodo, tarefa);
    InitializeComponent();
}

XAML

<pages:PopupPage 
         xmlns:animations="clr-namespace:Rg.Plugins.Popup.Animations;assembly=Rg.Plugins.Popup"
         xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:d="http://xamarin.com/schemas/2014/forms/design"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         mc:Ignorable="d"
         x:Class="Taskinho.Views.Popups.PopupView"
         xmlns:pages="clr-namespace:Rg.Plugins.Popup.Pages;assembly=Rg.Plugins.Popup">
    <StackLayout>
        <Label HorizontalOptions="Center" Text="{Binding test}" />
        <Button Text="{Binding tarefa.TarefaTitulo}" Command="{Binding Confirmar}" />
    </StackLayout>
</pages:PopupPage>

ViewModel

//Property
private Tarefa _Tarefa;
public Tarefa tarefa
{
    get { return _Tarefa; }
    set { _Tarefa = value;
        NotifyPropertyChanged("Tarefa");
    }
}
//another property
public string test = "Test Name";


//Constructor
public PopupViewModel(Func<bool> metodoParam, Tarefa TarefaParam)
{            
    this.tarefa = new Tarefa();
    ExecutarCommand = new Command(ExecutarAction);
}

//The binded Command(Not finded by the binding)
public Command ExecutarCommand
{
    get;
    set;
}
//Action of Command
void ExecutarAction()
{
    //do something
}

Я пытался использовать Path = ""и Source = "" при связывании кнопок, но я не знаю, как использовать в этой ситуации.

Ссылка на проект Открыть / Публично в Git

Спасибо

1 Ответ

1 голос
/ 01 ноября 2019

Тест свойства Text надписи <-binding-> метки (ниже для кода) не работает, но свойство Text для Button i делает привязку к другому объекту, отправленному в эту viewModel, и работает нормально. Я просто хотел бы понять, почему Binding не работает как обычно

Во-первых, вы можете связать только свойство, а не поле. замените ваш код:

 private string _test;
    public string test
    {
        get { return _test; }
        set
        {
            _test = value;
            NotifyPropertyChanged("test");
        }
    }   
    public PopupViewModel(Func<bool> metodoParam, Tarefa TarefaParam)
    {
        this.tarefa = new Tarefa();
        ExecutarCommand = new Command(ExecutarAction);
        test = "this is test!";
    }

О Path = "" и Source = "", я сделаю один пример для вас.

Вот класс представления модели:

public class viewmodel1: INotifyPropertyChanged
{
    private string _test;
    public string test
    {
        get
        {
            return _test;
        }
        set
        {
            _test = value;
            RaisePropertyChanged("test");
        }
    }
    public  Command command1 { get; set; }

    public viewmodel1()
    {
        test = "this is test!";
        command1 = new Command(method1);
    }

    private void method1()
    {
        Console.WriteLine("this is test!!!!!!!");
    }


    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisePropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }


}

Вот вид:

<ContentPage
x:Class="demo2.simplecontrol.Page18"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:model="clr-namespace:demo2.simplecontrol">
<ContentPage.BindingContext>
    <model:viewmodel1 x:Name="data1" />
</ContentPage.BindingContext>
<ContentPage.Content>
    <StackLayout>
        <Label
            HorizontalOptions="CenterAndExpand"
            Text="{Binding Path=test, Source={x:Reference data1}}"
            VerticalOptions="CenterAndExpand" />

        <Button Command="{Binding Path=command1, Source={x:Reference data1}}" Text="click1" />
    </StackLayout>
</ContentPage.Content>

Более подробную информацию, вы можете посмотреть:

https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/data-binding/binding-path

Если мой ответ поможетпожалуйста, не забудьте пометить мой ответ как ответ, спасибо.

...