本篇文章簡單介紹UWP MVVM 如何在view中使用view以外的資源(以加入Converter 為例)
假設view上有個 Image 元件, 它的Visibility屬性被綁定在MyViewModel.IsHide 這個Property上,
<Image
Margin="200,200,0,0"MaxWidth="50"MaxHeight="50"HorizontalAlignment="Center"VerticalAlignment="Center"Source="ms-appx:///Assets/googleIcon.png"Visibility="{Binding IsHide, Mode=OneWay}"/>
為了提升可讀性, 我們將 MyViewModel.IsHide 宣告成布林型別,
但由於 Visibility 屬性只能接受整數型別, 所以我們需要多做一個Converter 來轉換成UI上需要的值
public class BoolToIntConvert: IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { return (bool)value == true ? Visibility.Collapsed : Visibility.Visible; } public object ConvertBack(object value, Type targetType, object parameter, string language) { throw new NotImplementedException(); } }
問題是, 如何讓view 使用這個外部類別(BoolToIntConvert)呢
先宣告Converter 的路徑
標明Converter的Namespace<page xmlns:converters="using:MyUwpExample.ViewModels.Converters"
...
在XAML中使用BoolToIntConvert
我們必須先把它讀進來然後給它一個Key值<Page.Resources> <converters:BoolToIntConvert x:Key="BoolToVisibilityConverter"/> </Page.Resources>
使用BoolToIntConvert
透過給定的Key值, 以StaticResource的方式來使用BoolToIntConvert
Converter={StaticResource BoolToVisibilityConverter}
<Image
Margin="200,200,0,0"MaxWidth="50"MaxHeight="50"HorizontalAlignment="Center"VerticalAlignment="Center"Source="ms-appx:///Assets/googleIcon.png"Visibility="{Binding IsHide, Mode=OneWay, Converter={StaticResource BoolToVisibilityConverter}}"/>
完整程式碼如下
<Page x:Name="ListItemPage" x:Class="MyUwpExample.Views.ListPhotos" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:MyUwpExample.Views" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:converters="using:MyUwpExample.ViewModels.Converters" mc:Ignorable="d"> <Page.Resources> <converters:BoolToIntConvert x:Key="BoolToVisibilityConverter"/> </Page.Resources> <Grid> <ImageMargin="200,200,0,0"MaxWidth="50" MaxHeight="50"HorizontalAlignment="Center" VerticalAlignment="Center"Source="ms-appx:///Assets/googleIcon.png"Visibility="{Binding IsHide, Mode=OneWay, Converter={StaticResource BoolToVisibilityConverter}}"/> </Grid>
https://docs.microsoft.com/zh-tw/windows/uwp/data-binding/data-binding-in-depth
https://blogs.msdn.microsoft.com/johnshews_blog/2015/09/09/a-minimal-mvvm-uwp-app/
留言
張貼留言