For this you need to use Binding. So take a quick approach:
Here is the code for this:
public partial class MainWindow : Window { public bool ButtonIsVisible { get { return (bool)GetValue(ButtonIsVisibleProperty); } set { SetValue(ButtonIsVisibleProperty, value); } }
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 whole 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 weird binding syntax when buttons are visible. Why is this? I suggested that you do not need this functionality in the Model, so I returned to the DataContext DataGrid to achieve this DependencyProperty. I'm not quite sure about your scenario, but I have shown you some mechanisms that can be easily used.