7

I have the following .xaml for DataGrid and want to show/hide button on certain condition in .cs code .xaml code is as below

<DataGridTemplateColumn Header="Action" Width="auto" >
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Button x:Name="btnConfirm" Content="Confirm" Click="ConfirmButton_Click"  Height="auto" Width="auto"  Opacity="100" Background="Transparent" BorderBrush="Transparent" HorizontalAlignment="Left"/>
                <Button x:Name="btnDecline" Content="Decline" Click="btnDecline_Click" Height="auto" Width="auto"  Opacity="100" Background="Transparent" BorderBrush="Transparent" HorizontalAlignment="Left" />
                <Button x:Name="btnCancel" Content="Cancel" Click="btnCancel_Click" Height="auto" Width="auto"  Opacity="100" Background="Transparent" BorderBrush="Transparent" HorizontalAlignment="Left"/>
            </StackPanel>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

and .cs code is as

foreach (sp_ProcessingJobsResult item in grdUnConfirmJobs.ItemsSource)
{
var row = grdUnConfirmJobs.ItemContainerGenerator.ContainerFromItem(item) as System.Windows.Controls.DataGridRow;
if (item.Status == "Cancellation Requested.")
    {
      //how find control    
    }
}
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Jun 12 '15 at 07:29
  • possible duplicate of http://stackoverflow.com/questions/19379946/how-to-access-a-control-within-data-template-from-code-behind – Ahmad Jun 12 '15 at 07:43

1 Answers1

0

You have to use Binding for this. So, let's take a fast approach:

Here is the code behind for this:

public partial class MainWindow : Window
{
    public bool ButtonIsVisible
    {
        get { return (bool)GetValue(ButtonIsVisibleProperty); }
        set { SetValue(ButtonIsVisibleProperty, value); }
    }

    // Using a DependencyProperty as the backing store for ButtonIsVisible.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty ButtonIsVisibleProperty =
        DependencyProperty.Register("ButtonIsVisible", typeof(bool), typeof(MainWindow), new UIPropertyMetadata(true));

    public ObservableCollection<Person> items { get; set; }

    public MainWindow()
    {
        InitializeComponent();
        items = new ObservableCollection<Person>();
        items.Add(new Person() { Name = "FirstName" });
        items.Add(new Person() { Name = "SecondName" });

        this.DataContext = this;
    }
}

This is the Model for my example:

public class Person : INotifyPropertyChanged
{
    private string _Name;

    public string Name
    {
        get { return _Name; }
        set
        {
            _Name = value;
            PropertyChanged(this, new PropertyChangedEventArgs("Name"));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged = delegate { };
}

Your Visibility is not a bool type so we need a Converter for this:

public class BoolToVis : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var isVisible = (bool)value;

        return isVisible ? Visibility.Visible : Visibility.Hidden;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

And here is the entire XAML code:

<Window x:Class="DataGridCellsBackground.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    xmlns:local="clr-namespace:DataGridCellsBackground"        >
<Grid>
    <Grid.Resources>
        <local:BoolToVis x:Key="BoolTovisibilityConverter"/>
    </Grid.Resources>
    <DataGrid SelectionUnit="Cell" 
              ItemsSource="{Binding items}" 
              AutoGenerateColumns="False">
        <DataGrid.Resources>
        </DataGrid.Resources>
        <DataGrid.Columns>
            <DataGridTemplateColumn>
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Name}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTemplateColumn>
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Button Content="Visible" Visibility="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}, Path=DataContext.ButtonIsVisible, Converter={StaticResource BoolTovisibilityConverter}}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>
</Grid>

Indeed you see a strange Binding syntax at the Buttons Visibility. Why is that? I assumed you don't need this functionality in the Model so i got back to the DataContext of the DataGrid in order to reach that DependencyProperty. I am not completely sure about your scenario but i've shown you some mechanisms to be easily used.

Olaru Mircea
  • 2,570
  • 26
  • 49