네, 여러 가지 방법으로 수행 할 수 있습니다. 하나는 입력 유형에 따라 값을 선택하는 사용자 지정 "typeswitch"변환기를 작성하는 것입니다. 이처럼 : 다음
public class TypeSwitchConverter : Dictionary<Type, object>, IValueConverter
{
public object Convert(object value, Type targetType, object parameter, .CultureInfo culture)
{
foreach (var mapping in this)
{
if (mapping.Key.IsAssignableFrom(value.GetType()))
{
return mapping.Value;
}
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
그리고 당신의 셀 템플릿의 최상위 요소의 Style
바인딩을 사용하고, 필요에 따라 바인딩을 위해 위의 컨버터를 사용합니다.
<ListBox ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}">
<TextBlock.Style>
<Binding>
<Binding.Converter>
<my:TypeSwitchConverter>
<Style x:Key="{x:Type cor:Int32}" TargetType="{x:Type TextBlock}">
<Setter Property="Background" Value="Red" />
</Style>
<Style x:Key="{x:Type cor:String}" TargetType="{x:Type TextBlock}">
<Setter Property="Background" Value="Green" />
</Style>
<Style x:Key="{x:Type sys:Uri}" TargetType="{x:Type TextBlock}">
<Setter Property="Background" Value="Blue" />
</Style>
</my:TypeSwitchConverter>
</Binding.Converter>
</Binding>
</TextBlock.Style>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
빠른 답장을 보내 주셔서 감사합니다. 문제는 항목 컬렉션의 유형에 따라 스택 패널에 다른 컨트롤을 추가하려는 것입니다. 어떻게 해결할 수 있니? 그래서의 경우 에 ItemsCollection의 유형에 따라 다른 컨트롤 객체를 추가해야합니다. –
그런 다음 위의 'TypeSwitchConverter'를 사용하여 다른 템플릿에 'ItemTemplate' 속성을 바인딩하십시오. –
사실, 죄송 합니다만, 약간의 수정 - 'ItemTemplate'을 설정할 때 현재 항목이 없으므로 직접 바인딩 할 수 없습니다. 따라서 어떤 유형의 단일 요소 (예 :'ContentPresenter')를 포함하는 'ItemTemplate'을 정의한 다음 스위치 변환기를 사용하여 해당 요소의 'Template'속성을 바인딩합니다. –