INotifyPropertyChanged
public interface INotifyPropertyChanged
{
event PropertyChangedEventHandler PropertyChanged;
}
ICommandpublic interface ICommand
{
void Execute(object arg);
bool CanExecute(object arg)
event EventHandler CanExecuteChanged;
}
Modelnamespace MVVMPractice
{
public class XF4_CommandModel
{
public string DemoData { get; set; }
}
}
ViewModel// ICommand Interface 在該 namespace
using System.Windows.Input;
// Command 在該 namepspace
using Xamarin.Forms;
// INotifyPropertyChanged 在該 namespace
using System.ComponentModel;
namespace MVVMPractice
{
public class XF4_CommandViewModel : INotifyPropertyChanged
{
private XF4_CommandModel _model = new XF4_CommandModel();
public string DemoData
{
get { return _model.DemoData; }
set { _model.DemoData = value; }
}
public string _result;
public string Result
{
get { return _result; }
set
{
_result = value;
// 要有 OnPropertyChanged lblResult 才會顯示資料喔
OnPropertyChanged(nameof(Result));
}
}
public ICommand CmdSave
{
get
{
return new Command(() =>
{
Result = $"使用者輸入資料為:{_model.DemoData}";
});
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string PropertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
}
}
}
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"
xmlns:local="clr-namespace:MVVMPractice"
x:Class="MVVMPractice.XF4_Command">
<ContentPage.Content>
<StackLayout VerticalOptions="Center">
<!--Entry.Mode 預設就是為 TwoWay-->
<Entry Placeholder="請輸入資料" Text="{Binding DemoData}"/>
<Button Command="{Binding CmdSave}" Text="顯示輸入資料"/>
<Label x:Name="lblResult" Text="{Binding Result}" FontSize="Large"/>
</StackLayout>
</ContentPage.Content>
</ContentPage>
執行結果
沒有留言:
張貼留言