버튼을 Click 한 이벤트를 ViewModel 의 Command 에 binding 하고, 이때 CommandParameter를 전달하는 방법이다.
이 때 전달하는 Parameter는 string 으로 입력을 하므로, 다른 타입으로 변환하여 전달하고 싶으면 Coverter를 정의해야한다.
간단하게 string to double converter를 구현하고 이를 CommandParameter의 내부 converter 속성에 conveter를 입력한다.
<!-- 1. Static 값을 Parameter로 전달 StringCommand와 Binding -->
<Button Command="{Binding StringCommand}" CommandParameter="-5.0"/>
<!-- 2. Static 값을 Parameter로 전달 ObjectCommand와 Binding -->
<Button Command="{Binding ObjectCommand}" CommandParameter="-5.0"/>
<!-- 3. ViewModel의 string Property 와 binding -->
<Button Command="{Binding StringCommand}"
CommandParameter="{Binding ZoomLevel}"/>
<!-- 4. View의 Control의 속성값을 binding 및 Converter 연결 -->
<Button Command="{Binding DoubleCommand}"
CommandParameter="{Binding Text, ElementName=zoomlevel,
Converter={StaticResource StringToDoubleConverter}}"/>
<!-- ViewModel 의 string property 와 binding 되어 있는 textbox -->
<TextBox x:Name="zoomlevel" Text="{Binding ZoomPercentage, StringFormat='{}{0}'}"/>
1, 2의 tag의 경우에는 CommandParameter는 string 으로만 입력할 수 있으므로, 매개변수를 string 또는 object 를 갖는 command 와 연결할 수 있다. 다른 것은 전달되는 타입만 다를뿐 값은 동일하다.
3번은 CommandParater를 Property와 binding 하여 전달하는 것이다.
4번은 View의 control와 binding 하여 Command Parameter를 전달한다. 4번은 string을 double로 convert 하므로 Binding command는 double을 매개변수로 갖는 command 함수이다.
아래는 Static 값을 전달하면서 이를 converter를 수행 후 변환 된 값을 command 와 binding 하는 방법이다.
위의 1,2 번방법으로 수행하려고 하였으나, 이렇게는 동작을 하지 않았다.
그래서 찾은 방법이 behavior의 interaction 클래스를 이용하여 trigger를 명시하여 command를 binding 하도록 하였더니 원하는 동작이 되었다.
<UserControl.Resources>
<converters:StringToDoubleConverter x:Key="StringToDoubleConverter" />
</UserControl.Resources>
----------------------------
<Button Width="32"
Height="32 "
Margin="2"
Foreground="{DynamicResource MahApps.Brushes.Accent}"
Style="{StaticResource MahApps.Styles.Button.Circle}">
<b:Interaction.Triggers>
<b:EventTrigger EventName="Click">
<b:InvokeCommandAction Command="{Binding ZoomDoubleCommand}" CommandParameter="{Binding Source='-2.0', Converter={StaticResource StringToDoubleConverter}}">
</b:InvokeCommandAction>
</b:EventTrigger>
</b:Interaction.Triggers>
<Button.ContentTemplate>
<DataTemplate>
<iconPacks:PackIconRemixIcon Kind="CloseLine" />
</DataTemplate>
</Button.ContentTemplate>
</Button>
// ViewModel
ZoomDoubleCommand = new RelayCommand<double>(OnZoomDouble);