A
A
Anton Pronin2015-06-07 07:37:16
C++ / C#
Anton Pronin, 2015-06-07 07:37:16

How to translate XAML into code?

Good day, I stumbled on the following problem. There is xaml that works as it should, namely, by clicking on the column header, it displays a menu with all columns

<UserControl.Resources>
 <ContextMenu x:Key="ColumnMenu" 
                     ItemsSource="{Binding Columns}" 
                     DataContext="{Binding DataContext, 
                                            RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}">
            <ContextMenu.ItemContainerStyle>
                <Style TargetType="{x:Type MenuItem}">
                    <Setter Property="IsChecked" Value="{Binding Visibility,Converter={StaticResource Vt}}"></Setter>
                    <Setter Property="Command" Value="{Binding DataContext.ChangeVisibleColumnCommand, 
                                RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" ></Setter>
                    <Setter Property="CommandParameter" Value="{Binding}"></Setter>
                </Style>
            </ContextMenu.ItemContainerStyle>
            <ContextMenu.ItemTemplate>
                <DataTemplate DataType="MenuItem">
                    <MenuItem Header="{Binding Header}"></MenuItem>
                </DataTemplate>
            </ContextMenu.ItemTemplate>
        </ContextMenu>
</UserControl.Resources>
<DataGrid Context={StaticResouce ContextMenuRow}>
   <DataGrid.Resources>
           <Style TargetType="{x:Type DataGridColumnHeader}">
                <Setter Property="ContextMenu" Value="{StaticResource ColumnMenu}"/>
            </Style>
    </DataGrid.Resources>
</DataGrid>

translate this C# code
var columMenu = new ContextMenu();
columMenu.SetBinding(System.Windows.Controls.ContextMenu.ItemsSourceProperty, new Binding("Columns"));
var menu = new ContextMenu();
menu.SetBinding(System.Windows.Controls.ContextMenu.ItemsSourceProperty, new Binding("ContextMenuItems"));
var stl = new System.Windows.Style();
stl.Setters.Add(new Setter(DataGridColumnHeader.ContextMenuProperty, columMenu));            
dg.Style = stl;
dg.ContextMenu = menu;

Only menu reacts, but if you remove dg.ContextMenu = menu; then columMenu appears above the entire DataGrid
How to be?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vyacheslav Zolotov, 2015-06-07
@SZolotov

As they say, "With the help of simple devices, you can make a trolleybus from a loaf of bread. But why?" Why do UI through C#?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question