2010-05-14 5 views
1

시작해서 WPF 앱에 MVVM 패턴을 사용하고 있지 않다고 말하겠습니다. 용서해주세요.WPF에서 선택적 이중 명령 바인딩 변환기?

지금은 두 개의 버튼이있는 데이터 템플릿이 있고,이 데이터 템플릿이 나타내는 CLR 객체의 다른 명령에 각각 바인딩됩니다. 둘 다 동일한 명령 매개 변수를 사용합니다. 다음은 버튼의 예입니다.

<Button x:Name="Button1" 
     Command="{Binding Path=Command1}" 
     CommandParameter="{Binding Path=Text, ElementName=TextBox1}" 
/> 
<Button x:Name="Button2" 
     Command="{Binding Path=Command2}" 
     CommandParameter="{Binding Path=Text, ElementName=TextBox1}" 
/> 

이 설정을 Settings.settings에서 부울과 같은 사용자 설정에 따라 명령을 수행 할 수있는 단일 버튼으로 리팩토링하고 싶습니다. CLR 개체 자체를 리팩토링 할 수있는 권한이 없습니다. 또한 이것은 데이터 템플릿으로 작업 할 코드 숨김이 없습니다. 필자가 생각하기에 컨버터가 가장 좋은 방법 일 것이지만, 나는 그것을 어떻게 조합 할 것인지 모른다.

변환기에서 명령을 실행할 개체를 알 수 있도록 변환기에서 CommandParameter와 DataContext를 가져와야합니다.

누군가 내게 이것을 빌려줄 수 있습니까? 미리 감사드립니다.

답변

4

신속하고 더러운 솔루션 - 양식에 두 개의 버튼을 넣고 그 가시성을 bool 값에 바인딩합니다 (분명히 부정 된 것) - 유효한 버튼 만 표시됩니다.

변환기를 사용하려면 명령 바인딩에 사용하고 CLR 개체와 bool 값을 전달하여 바인드 할 올바른 명령을 반환 할 수 있어야합니다. . 명령 매개 변수를 전달할 아무 이유도 없기 때문에 두 가지 방법이 동일합니다.

XAML :

<Resources> 
    <controls:CommandConverter x:Key="CommandConverter"/> 
</Resources> 

<Button x:Name="Button" 
     CommandParameter="{Binding Path=Text, ElementName=TextBox1}"> 
    <Button.Command> 
     <MultiBinding Converter="{StaticResource CommandConverter}"> 
      <MultiBinding.Bindings> 
      <Binding /><-- the datacontext CLR object --> 
      <Binding ... /><-- Application setting (however you intend to get that in) 
      </MultiBinding.Bindings> 
     </MultiBinding> 
    </Button.Command> 
</Button> 

코드 :


public class CommandConverter : IMultiValueConverter 
{   
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) 
    { 
     CommandObject clrObject= (CommandObject)values[0]; 
     bool setting = (bool)values[1]; 

     if (setting) 
     { 
      return clrObject.Command1; 
     } 

     return clrObject.Command2; 
    } 

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) 
    { 
     throw new NotSupportedException(); 
    } 
} 
사실 설정 BOOL 그냥 응용 프로그램 설정에있는 경우 당신은 바로 계산기 만 사용 직접 사용할 수 있습니다 정상적인 단일 값 변환기. 정말 혼자 서 있어야하기 때문에 훌륭한 디자인이 아니지만 일을 끝내야합니다.

+0

물론! WPF 101에서 방금 실패했습니다. – Jippers