c#
wpf MVVM Commandparameter 여러 개 파라미터 받기
범백
2023. 1. 30. 22:56
wpf의 MVVM패턴 사용시 commandparameter의 값을 여러개를 받을때 사용 할 수 있는 코드입니다.
-소스는 저번에 사용한 ICommand활성화 비활성화를 가져다 썻습니다.
1.컨버터 코드 생성
//컨버터
class Converter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return values.Clone();
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
2.xaml 파일에서 컨버터를 리소스로 설정해주고 버튼에 멀티 바인딩 컨버터 지정.
<Button.CommandParameter>
<MultiBinding Converter="{StaticResource Converter}">//컨버터 리소스 사용
<Binding ElementName="Main"/> //첫번째 파라미터 Main object
<Binding Path="Height" ElementName="txlast"/>// 두번째 파라미터 텍스트박스 Height값
</MultiBinding>
</Button.CommandParameter>
<Window x:Class="WpfApp2.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp2"
mc:Ignorable="d"
Title="Window1" Height="450" Width="800"
Name="Main">
<Window.Resources>
<local:Converter x:Key="Converter"/>
</Window.Resources>
<Grid>
<TextBlock Text="{Binding Title}" HorizontalAlignment="Left" Margin="148 58 0 0" TextWrapping="Wrap" VerticalAlignment="Top" Height="20"></TextBlock>
<TextBlock Text="{Binding Num}" HorizontalAlignment="Left" Margin="148 103 0 0" TextWrapping="Wrap" VerticalAlignment="Top"></TextBlock>
<TextBox Text="{Binding Path=Num, Mode=TwoWay}" HorizontalAlignment="Left" Margin="364 58 0 0" TextWrapping="Wrap" VerticalAlignment="Top" Height="23" Width="120"></TextBox>
<TextBox Name="txlast" Text="참조" HorizontalAlignment="Left" Margin="364 103 0 0" TextWrapping="Wrap" VerticalAlignment="Top" Height="23" Width="120"></TextBox>
<Button Command="{Binding CheckCommand}" Content="Button" HorizontalAlignment="Left" Margin="364,151,0,0" VerticalAlignment="Top" Width="75">
<Button.CommandParameter>
<MultiBinding Converter="{StaticResource Converter}">
<Binding ElementName="Main"/>
<Binding Path="Height" ElementName="txlast"/>
</MultiBinding>
</Button.CommandParameter>
</Button>
</Grid>
</Window>
3. execute에 (object[])캐스팅을 통해 넘겨받은 파라미터를 확인해 봅니다.
public void Execute(object o)
{
var value = (object[])o;
var value1 = value[0];
var value2 = value[1];
this.execute();
}
디버깅
디버깅을 해보면 xaml에서 넘긴 첫번째 파라미터 object Window1이 넘어왔으며
두번째 파라미터로는 txtblock의 Height의 값이 넘어 왔습니다.