我有以下xaml:
<ListView x:Name="SomeClass_SomeListProperty">
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<WrapPanel VerticalAlignment="Center" HorizontalAlignment="Center">
<TextBlock Text="{Binding Type}"/> <!--This is a string-->
<TextBlock Text=": "/>
<TextBlock Text="{Binding Number}"/> <!--This is a long-->
</WrapPanel>
<Grid Grid.Column="1" HorizontalAlignment="Center">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Image Stretch="None"
Source="{Binding BoolThatDependsOnType,
Converter={StaticResource BoolToImageConverter},
ConverterParameter='large'}" />
<Button Grid.Column="1" Content="Settings"
cal:Message.Attach="MethodCallThatDependsOnType"/>
</Grid>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
我可以以某种方式绑定bool“BoolThatDependsOnType”,具体取决于Type的值吗?我遇到的问题是图像源的设置取决于某个bool是真还是假。我想选择要绑定的bool,具体取决于Type是否为特定列表项的“type1”,“type2”或“type3”。
答案 0 :(得分:0)
在@Clemens的启发下,我使用IMultiValueConverter
和MultiBinding
来找到以下解决方案(并且没有变量和方法名称不是实际使用的:-))。
public class TypeAndMultipleBoolsToImageConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values == null) return new BitmapImage(new Uri("some/path.png", UriKind.Relative));
bool isOk;
switch (((string) values[0]).ToLower(culture))
{
case "type1":
isOk = (bool) values[1];
break;
case "type2":
isOk = (bool) values[2];
break;
case "type3":
isOk = (bool) values[3];
break;
default:
return new BitmapImage(new Uri("/some/path.png", UriKind.Relative));
}
return ConvertBoolToImage(isOk);
}
private static BitmapImage ConvertBoolToImage(bool isOk)
{
return isOk
? new BitmapImage(new Uri("/some/ok/path.png", UriKind.Relative))
: new BitmapImage(new Uri("/some/not/ok/path.png", UriKind.Relative));
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
<Image Stretch="None">
<Image.Source>
<MultiBinding Converter="{StaticResource TypeAndMultipleBoolsToImageConverter}">
<Binding Path="Type"/>
<Binding Path="DataContext.IsType1Ok"
RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=UserControl}"/>
<Binding Path="DataContext.IsType2Ok"
RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=UserControl}"/>
<Binding Path="DataContext.IsType3Ok"
RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=UserControl}"/>
</MultiBinding>
</Image.Source>
</Image>