简体   繁体   中英

Turning a WPF DataGrid background image on and off?

I have a DataGrid which, when empty, I wish to display a background image. When the DataGrid is populated I wish for the image to disappear, and reappear if the DataGrid is cleared again.

Is this possible either through XAML or C#?

if(myDataGridView.Rows.Count == 0) {

dataGrid.Background = new ImageBrush("exampleImage.png");

}

else {

// it is not empty 

}

If you are using the MVVM design pattern, you should generally avoid using codebehind. Its fairly simple to do this in XAML though:

Put an Image element over the data grid (put the two together in a Grid and put the Image just below the DataGrid) and then bind the Visibility property of the Image to DataGrid's Items.Count property with a new converter:

<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>

The Converter would look like this:

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;
    }
}

I'm assuming you are using WPF, with Windows forms it will be very hard.

    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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM