Hi, @Lê quang Thắng. Welcome to Microsoft Q&A.
Solution:
1.Define DataGrid
in Resource
and use ContentPresenter
to present DataGrid
. In the code, use this.Resources["dataGrid"] as DataGrid;
to directly obtain DataGrid
.
2.Define DataContext
in "Resource" and bind it directly through "Visibility="{Binding Path=EnableB1,Source={StaticResource MyMainWindowViewModel},Mode=TwoWay}"
Here we assume that your ViewModel
is MainWindowViewModel
.
MainWindow.xaml
<Window.Resources>
<vm:MainWindowViewModel x:Key="MyMainWindowViewModel" x:Name="MyMainWindowViewModel"></vm:MainWindowViewModel>
<DataGrid x:Key="dataGrid" AutoGenerateColumns="False" CanUserAddRows="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Test Item" Binding="{Binding TestItem, Mode=TwoWay}">
<DataGridTextColumn.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="FontSize" Value="12"/>
<!--Set Font Size-->
<Setter Property="FontWeight" Value="Bold"/>
<!--Set Bold Font-->
</Style>
</DataGridTextColumn.CellStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="B1" Binding="{Binding B1, Mode=TwoWay}" Width="80" Visibility="{Binding Path=EnableB1,Source={StaticResource MyMainWindowViewModel},Mode=TwoWay}"/>
</DataGrid.Columns>
</DataGrid>
</Window.Resources>
<Grid>
<TabControl x:Name="tabControlMain" >
…
<ScrollViewer Grid.Row="0" Grid.Column="0" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto">
<ContentPresenter Content="{DynamicResource dataGrid}" ></ContentPresenter>
</ScrollViewer>
…
</TabControl>
</Grid>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindowViewModel mainWindowViewModel;
public MainWindow()
{
InitializeComponent();
//Note that `DataContext` should use the same
mainWindowViewModel = this.Resources["MyMainWindowViewModel"] as MainWindowViewModel;
tabControlMain.DataContext = mainWindowViewModel;
// Get directly to dataGrid
var dataGrid = this.Resources["dataGrid"] as DataGrid;
dataGrid.DataContext = mainWindowViewModel;
dataGrid.ItemsSource = mainWindowViewModel.TestData;
}
}
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
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.