Here is an example of binding ElementName in CheckBox, you could try it for reference.
MainWindow.xaml:
<Window.Resources>
<Style x:Key="cell" TargetType="DataGridCell">
<Setter Property="Background" Value="LightBlue"/>
</Style>
</Window.Resources>
<StackPanel>
<TextBlock Name="tb" Text="hello" Width="150" Background="LightSteelBlue"/>
<DataGrid Name="dg" ItemsSource="{Binding Persons}" AutoGenerateColumns="False" CellStyle="{StaticResource cell}">
<DataGrid.Resources>
<Style x:Key="BackgroundColourStyle" TargetType="{x:Type CheckBox}">
<Style.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter Property="Background" Value="LightGreen" />
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding ID}" />
<DataGridTextColumn x:Name="Name1" Header="Name" Binding="{Binding Name}"/>
<DataGridCheckBoxColumn x:Name="check" Header="{Binding ElementName=Name1,Path= Header}" Binding="{Binding Check}" ElementStyle="{StaticResource BackgroundColourStyle }"/>
<DataGridTemplateColumn x:Name="Check" >
<DataGridTemplateColumn.Header >
<CheckBox Content="SelectAll" x:Name="headerCheckBox" Background="{Binding ElementName=tb,Path=Background}" Width="{Binding ElementName=tb ,Path=Width}"/>
</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate >
<DataTemplate>
<CheckBox x:Name="CheckSelected" Background="Orange" IsChecked="{Binding IsChecked,ElementName=headerCheckBox,Mode=OneWay}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</StackPanel>
MainWindow.xaml.cs:
public partial class MainWindow : Window
{
public ViewMode viewmodel;
public MainWindow()
{
InitializeComponent();
viewmodel = new ViewMode();
this.DataContext = viewmodel;
}
}
public class ViewMode : INotifyPropertyChanged
{
public ObservableCollection<Person> Persons { get; set; }
public ViewMode()
{
Persons = new ObservableCollection<Person>();
Persons.Add(new Person { ID = 1, Name = "man", Check=true});
Persons.Add(new Person { ID = 2, Name = "john", Check = true});
Persons.Add(new Person { ID = 3, Name = "jo" , Check = false });
}
protected void OnPropertyChanged(string porpName)
{
var temp = PropertyChanged;
if (temp != null)
temp(this, new PropertyChangedEventArgs(porpName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
public class Person
{
public int ID { get; set; }
public String Name { get; set; }
public bool Check { get; set; }
}
The result:
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.