我有一个DataGrid,当它为空时,我希望显示一个背景图像。当填充DataGrid时,我希望图像消失,如果再次清除DataGrid,则重新出现。
这可以通过XAML还是C#?
答案 0 :(得分:2)
if(myDataGridView.Rows.Count == 0) {
dataGrid.Background = new ImageBrush("exampleImage.png");
}
else {
// it is not empty
}
答案 1 :(得分:2)
如果您使用的是MVVM设计模式,通常应该避免使用代码隐藏。在XAML中执行此操作非常简单:
将一个Image元素放在数据网格上(将两者放在一个Grid中并将Image放在DataGrid下面),然后使用新的转换器将Image的Visibility属性绑定到DataGrid的Items.Count属性:
<Grid>
<Grid.Resources>
<local:GridCountToVisibilityConverter x:Key="GridCountToVisibilityConverter"/>
</Grid.Resources>
<DataGrid x:Name="grid"/>
<Image Source="image.jpg" Visibility="{Binding ElementName=grid, Path=Items.Count, Converter={StaticResource GridCountToVisibilityConverter}}" />
</Grid>
转换器看起来像这样:
public class GridCountToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var count = (int)value;
return count == 0? Visibility.Visible : Visibility.Collapsed;
}
}
答案 2 :(得分:0)
我假设您正在使用WPF,使用Windows表单将非常困难。
System.Windows.Controls.DataGrid dataGrid = new System.Windows.Controls.DataGrid();
public void Initialize()
{
dataGrid.Loaded += new System.Windows.RoutedEventHandler(dataGrid_Loaded);
dataGrid.Unloaded += new System.Windows.RoutedEventHandler(dataGrid_Unloaded);
// Show image right away.
this.dataGrid_Unloaded(null, null);
}
void dataGrid_Unloaded(object sender, System.Windows.RoutedEventArgs e)
{
// Provide some image here.
dataGrid.Background = new System.Windows.Media.ImageBrush();
}
void dataGrid_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
dataGrid.Background = System.Windows.Media.Brushes.Gray;
}