所以我有一个带有图像列的DataGrid,我希望能够在Image具有有效(非空)源时隐藏“浏览...”超链接。怎么办?
这是我的XAML:
<DataGridTemplateColumn Header="Image">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Command="{Binding ChangeImageCommand}">
<Button.Template>
<ControlTemplate>
<Grid>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center">
<Hyperlink Command="{Binding ChangeImageCommand}">Browse...</Hyperlink>
</TextBlock>
<Image Source="{Binding Image}" Margin="0"/>
</Grid>
</ControlTemplate>
</Button.Template>
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
哦,如果有更简单的方法来实现备用文字的图像按钮,请告诉我! : - )
答案 0 :(得分:3)
默认情况下使TextBlock不可见,并为Image.Source == null
类似的东西:
<DataGridTemplateColumn Header="Image">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Command="{Binding ChangeImageCommand}">
<Button.Template>
<ControlTemplate>
<Grid>
<TextBlock Name="TextBlock" HorizontalAlignment="Center" VerticalAlignment="Center" Visibility="Collapsed">
<Hyperlink Command="{Binding ChangeImageCommand}">Browse...</Hyperlink>
</TextBlock>
<Image Name="Image" Source="{Binding Image}" Margin="0"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger SourceName="Image"
Property="Source"
Value="{x:Null}">
<Setter TargetName="TextBlock"
Property="Visibility"
Value="Visible"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Button.Template>
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
答案 1 :(得分:1)
您可以使用ValueConverter将Image绑定到Visibility。基于null工作的简单转换器如下所示:
public class VisibilityConverter : IValueConverter
{
public Visibility True { get; set; }
public Visibility False { get; set; }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return (value != null ? True : False);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
您可以在XAML资源中创建一些此实例,以用于控制元素的可见性。此外,您不需要模板按钮,因为WPF按钮可以包含您喜欢的任何内容(而不仅仅是文本)。所以你的XAML看起来像这样:
<Window.Resources>
<loc:VisibilityConverter x:Key="ImageConverter" True="Visible" False="Collapsed"/>
<loc:VisibilityConverter x:Key="BrowseConverter" True="Collapsed" False="Visible"/>
</Window.Resources>
. . .
<DataGridTemplateColumn Header="Image">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Command="{Binding ChangeImageCommand}">
<Grid>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center"
Visibility="{Binding Image, Converter={StaticResource BrowseVisibility}}">
Browse...
</TextBlock>
<Image Source="{Binding Image}" Margin="0"
Visibility="{Binding Image, Converter={StaticResource ImageVisibility}}"/>
</Grid>
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
请注意,您还需要在XAML顶部create the loc namespace。而且我以为你会把它们放在你的Window资源中。