ロジックコードの記述
Visual StudioのソリューションエクスプローラーでModelsフォルダを作成します。ここで新たにクラスファイルを作成してもいいのですが、Windowsフォームアプリで作ったJPAddressModel.vbを取り込んで使ってみましょう。Modelsフォルダを右クリックして[追加]‐[既存の項目]メニューでクラスファイルを追加します。
画面連結用クラスの作成
画面連結用クラスについても同様にWindowsフォームアプリで作成したものを取り込みます。取り込んだものにWPF特有のCommandバインディング用のコードを追加します。
Imports System.ComponentModel
Imports GrapeCity.Win.JPAddress
Public Class MainViewModel
Implements INotifyPropertyChanged
:
(略)
:
'Public Sub GetAddress(postCode)
' Call Me.VmModel.GetAddress(postCode)
'End Sub
Private _getAddressCommand As ICommand
Public ReadOnly Property GetAddress As ICommand
Get
If Me._getAddressCommand Is Nothing Then
Me._getAddressCommand = New GetAddressCommand(Me)
End If
Return Me._getAddressCommand
End Get
End Property
Private Class GetAddressCommand
Implements ICommand
Private _viewModel As MainViewModel
Public Sub New(viewModel As MainViewModel)
_viewModel = viewModel
AddHandler _viewModel.PropertyChanged, AddressOf ViewModel_Changed
End Sub
Public Function CanExecute(parameter As Object) As Boolean _
Implements ICommand.CanExecute
Return (String.IsNullOrEmpty(Nothing))
End Function
Public Event CanExecuteChanged(sender As Object,
e As EventArgs) _
Implements ICommand.CanExecuteChanged
Private Sub ViewModel_Changed(sender As Object, e As EventArgs)
RaiseEvent CanExecuteChanged(sender, e)
End Sub
Public Sub Execute(parameter As Object) Implements ICommand.Execute
Dim postcode As String = parameter.ToString.Replace("-", "")
Me._viewModel.VmModel.GetAddress(postcode)
End Sub
End Class
End Class
画面の作成
今回のサンプルでは、郵便番号欄、検索ボタン、検索結果一覧という画面構成にします。
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="MainWindow"
Title="JPAddress Sample" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" Grid.Row="0"
x:Name="PostCode_TextBox" Text="981-3205" Margin="10" />
<Button Grid.Column="1" Grid.Row="0"
Content="住所検索" Margin="10"
Command="{Binding GetAddress}"
CommandParameter="{Binding Text, ElementName=PostCode_TextBox}"/>
<DataGrid Grid.Column="0" Grid.Row="1" Grid.ColumnSpan="3"
AutoGenerateColumns="False" IsReadOnly="True"
ItemsSource="{Binding Address}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Prefecture}" Header="都道府県" />
<DataGridTextColumn Binding="{Binding City}" Header="市区町村" />
<DataGridTextColumn Binding="{Binding Town}" Header="町" />
<DataGridTextColumn Binding="{Binding Area}" Header="町域" />
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>

