星期二, 8月 22, 2017

[X.Form] MVVM - Command - 參數傳遞

[X.Form] MVVM 簡易練習 內 Entry 是 Binding 到 ViewModel 內,Button Command 直接抓 ViewModel Property 來呈現資料,該篇文章 Simplifying Events with Commanding 是 Button Command 直接抓 Entry View 來呈現資料,練習一下

View Model
using System.ComponentModel;
using System.Windows.Input;
using Xamarin.Forms;

namespace MVVMPractice
{
    public class XF42_CommandViewModel : INotifyPropertyChanged
    {
        public ICommand CmdSave { get; set; }

        public string ShowUserInputMessage { get; set; }

        public XF42_CommandViewModel()
        {
            CmdSave = new Command<string>(UserInputMessage);
        }

        private void UserInputMessage(string Value)
        {
            ShowUserInputMessage = $"使用者輸入為 {Value}";
            OnPropertyChanged(nameof(ShowUserInputMessage));
        }

        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"
             x:Class="MVVMPractice.XF42_Command">
    <ContentPage.Content>
        <StackLayout VerticalOptions="Center">
            <Entry x:Name="entry" Text="Xamarin Command 練習"/>
            <Button Text="顯示使用者輸入"
                Command="{Binding CmdSave}"
                CommandParameter="{Binding Source={x:Reference entry} , Path=Text}">
            </Button>
            <Label Text="{Binding ShowUserInputMessage}" FontSize="Large"></Label>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

[X.Form] Command - 參數傳遞
  • 練習烏龍事件
因為是在練習,所以就直接從上個練習中把 PropertyChangedEventHandler 和 OnPropertyChanged() Copy 過來使用,實際測試時,發現 ViewModel 內呼叫 OnPropertyChanged(),View 上竟然都不會變化,用中斷點觀察才發現到,原來 PropertyChangedEventHandler 為 null,原因是該 ViewModel 忘記實作 INotifyPropertyChanged Interface,偷懶的下場,Orz

[X.Form] Command - 參數傳遞-2

沒有留言:

張貼留言