I have created an UserControl for reusability in my program:
GroupPanel.xaml:
<UserControl x:Class="View.UserControls.GroupPanel"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"assembly=ViewModel"
Name="root">
<DockPanel>
<DataGrid DockPanel.Dock="Top"
AutoGenerateColumns="False"
CanUserAddRows="True"
CanUserDeleteRows="False"
CanUserReorderColumns="False"
DataContext="{Binding ElementName=root}"
ItemsSource="{Binding DataGridItemSource}"
Name="mainGrid">
<DataGrid.Columns>
<DataGridTextColumn Header="Nr/Unit"
Binding="{Binding Nr}" />
<DataGridTextColumn Header="Text"
Binding="{Binding Text}" />
<DataGridTextColumn Header="Comment"
Binding="{Binding Comment}" />
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Button Content="Delete" />
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</DockPanel>
and a Dependency Property to set the DataGrid's ItemsSource:
GroupPanel.xaml.cs:
public static readonly DependencyProperty DataGridItemSourceProperty =
DependencyProperty.Register("DataGridItemSource", typeof(IEnumerable), typeof(GroupPanel),
new PropertyMetadata(null));
public IEnumerable DataGridItemSource
{
get { return (IEnumerable)GetValue(DataGridItemSourceProperty); }
set { SetValue(DataGridItemSourceProperty, value); }
}
I have a window where I need this UserControl 2 times with different ItemsSources to bind. But both Sources have the same properties up to first property. The sources are:
GroupNumber:
Number, int
Text, string
Comment, string
GroupUnit:
Unt, int
Text, string
Comment, string
The behaviour is the same for both of them. Is there a way to set the 1 DataGrid column's binding depending on the ItemsSource?
I have tried something like this:
void GroupPanel_Loaded(object sender, RoutedEventArgs e)
{
var type = DataGridItemSource.GetType();
if(type.FullName.Contains("GroupNumber"))
{
}
}
But I don't know how to set the columns binding inside the if...
Thank you in advance
DataTemplate. You don't need anUserControlhere, you can just define aStylefor yourDataGridand reuse it. - dymanoidDataGridcolumns programmatically is not the way to go. You'll often end up with duplicated sections of XAML, but believe me... you'll make it easier on yourself in the long run if you just accept that fact. It is possible though. See theDataGrid.AutoGeneratingColumnEvent page on MSDN. - Sheridan