Custom MenuItem style for ContextMenu? - c#

I need to create a custom style for MenuItem with a set of ControlTemplate per each MenuItem Role. So, I decided to use this approach from msdn
But, there's one problem - I want to get the same appearance in Popup.
Unfortunately, the appearance is different like on the picture below:
Example of code:
<Window x:Class="ExporerSubMenu.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ExporerSubMenu"
mc:Ignorable="d"
Title="MainWindow" Height="400" Width="1000">
<Window.Resources>
<!-- Copy all styles for MenuItem ControlTemplate and Brushes -->
<!-- https://msdn.microsoft.com/fr-fr/library/ms747082(v=vs.85).aspx -->
</Window.Resources>
<Grid Background="LightBlue">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBox Text="Local (right click)" FontSize="16" Grid.Column="0">
<TextBox.ContextMenu>
<ContextMenu>
<MenuItem Header="Restore...">
<MenuItem Header="to desktop" />
<MenuItem Header="to another folder" />
<MenuItem Header="db schema and data..." />
</MenuItem>
<MenuItem Header="to .bac file">
<MenuItem Header="to desktop" />
<MenuItem Header="to another folder" />
</MenuItem>
<MenuItem Header="to db files">
<MenuItem Header="to desktop" />
<MenuItem Header="to another folder" />
</MenuItem>
<MenuItem Header="Export data">
<MenuItem Header="db schema to desktop" />
<MenuItem Header="db schema and data..." />
</MenuItem>
<MenuItem Header="Remove" />
</ContextMenu>
</TextBox.ContextMenu>
</TextBox>
</Grid>
</Window>
Now, I have only one solution - to draw rectangles (from Blend)
<Popup x:Name="PART_Popup" AllowsTransparency="True" Focusable="False" HorizontalOffset="-2" IsOpen="{Binding IsSubmenuOpen, RelativeSource={RelativeSource TemplatedParent}}" PopupAnimation="{DynamicResource {x:Static SystemParameters.MenuPopupAnimationKey}}" Placement="Right" VerticalOffset="-3">
<Themes:SystemDropShadowChrome x:Name="Shdw" Color="Transparent">
<Border x:Name="SubMenuBorder" BorderBrush="#FF959595" BorderThickness="1" Background="WhiteSmoke">
<ScrollViewer x:Name="SubMenuScrollViewer" Margin="1,0" Style="{DynamicResource {ComponentResourceKey ResourceId=MenuScrollViewer, TypeInTargetAssembly={x:Type FrameworkElement}}}">
<Grid x:Name="Grid2" RenderOptions.ClearTypeHint="Enabled">
<Canvas x:Name="Canvas" HorizontalAlignment="Left" Height="0" VerticalAlignment="Top" Width="0">
<Rectangle x:Name="OpaqueRect" Fill="WhiteSmoke" Height="{Binding ActualHeight, ElementName=SubMenuBorder}" Width="{Binding ActualWidth, ElementName=SubMenuBorder}"/>
</Canvas>
<Rectangle x:Name="Rectangle" Fill="#FFF1F1F1" HorizontalAlignment="Left" Margin="1,2" RadiusY="2" RadiusX="2" Width="28"/>
<Rectangle x:Name="Rectangle1" Fill="#FFE2E3E3" HorizontalAlignment="Left" Margin="29,2,0,2" Width="1"/>
<Rectangle x:Name="Rectangle2" Fill="White" HorizontalAlignment="Left" Margin="30,2,0,2" Width="1"/>
<ItemsPresenter x:Name="ItemsPresenter" KeyboardNavigation.DirectionalNavigation="Cycle" Grid.IsSharedSizeScope="True" Margin="2" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" KeyboardNavigation.TabNavigation="Cycle"/>
</Grid>
</ScrollViewer>
</Border>
</Themes:SystemDropShadowChrome>
</Popup>
Is there any another solution to solve this ?

Related

Align right menu item inside a stackpanel WPF

i'm making a simple WPF application and i'm facing a problem.
I have a StackPanel that contain a Menu and a StackPanel and i'm trying to align certains MenuItem to right but with no success...
I trying to do something like that :
===================================================
FILE .....................................................REDUCE MINIMIZE CLOSE --->MENU
APPTITLE ---------------------------------------------> Stackpanel
There is another StackPanel that contain both elements to align them Vertically
I tried differents way, with my menu item in a stackpanel or dockpanel...
Here is my MainWindow.xaml :
<StackPanel Orientation="Vertical">
<Menu materialDesign:RippleAssist.IsDisabled="True" Name="menu" Height="40" Foreground="#FF060000" BorderBrush="#FFED0303">
<MenuItem HorizontalAlignment="Center" VerticalAlignment="Center" Header="_Fichier">
<MenuItem Header="_Quitter" Click="ExitButton_Click">
<MenuItem.Icon>
<Image Source="assets/images/quitter.png"></Image>
</MenuItem.Icon>
</MenuItem>
</MenuItem>
<MenuItem Click="minimize_Click" Height="15" Width="19" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,0,0,5">
<MenuItem.Background>
<ImageBrush ImageSource="assets/images/minimize.png"/>
</MenuItem.Background>
</MenuItem>
<MenuItem Click="maximize_Click" Height="15" Width="19" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="11,10,0,0">
<MenuItem.Background>
<ImageBrush x:Name="resizeImage" ImageSource="{Binding ResizeImagePath}"/>
</MenuItem.Background>
</MenuItem>
<MenuItem Click="ExitButton_Click" Height="20" Width="19" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="11,10,0,0">
<MenuItem.Background>
<ImageBrush ImageSource="assets/images/close.png"/>
</MenuItem.Background>
</MenuItem>
</Menu>
<StackPanel Orientation="Horizontal" Margin="0,14,0,0" VerticalAlignment="Center">
<Button Margin="10,0,0,0" Click="scanNetwork_Click" BorderBrush="{x:Null}">
<Button.Background>
<ImageBrush ImageSource="assets/images/756363-200.png"/>
</Button.Background>
</Button>
<TextBlock Text="Machine Sniffer" HorizontalAlignment="Left" VerticalAlignment="Center" FontSize="24" FontWeight="Bold" FontFamily="{DynamicResource MaterialDesignFont}" Foreground="White" Margin="10,0,0,0"></TextBlock>
</StackPanel>
</StackPanel>
The actual result is something like that :
===================================================
FILE REDUCE MINIMIZE CLOSE --->MENU
APPTITLE ---------------------------------------------> Stackpanel
Thanks for help
In StackPanel you are not able to adjust items to te right like you are doing, they not allow alignment in the direction in which they stack.
You can use a Grid or a DockPanel instead:
Example with DockPanel:
<DockPanel Width="300">
<!-- place menu items here and use the VerticalAlignment property like you're doing -->
</DockPanel>
Example with Grid:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<!-- place elements here and indicate respective column -->
</Grid>

Binding Items collection on Menu to be shown on MenuItem Popup

I have the need to have a custom Menu (AMTMenu class inheriting Menu plus some additional DependencyProperties) with a MenuItem (a hamburger button actually) with dynamic children, since this menu is to be reused in a lot of layouts. Other than that, it should show other 5 TopLevel menu items that display info contained on the DataContext without any children attached and a refresh button. It's working fine except for the sub menu part which is not being shown when I click the hamburger MenuItem because I can't seem to bind the items correctly. Here's the code I have so far:
<Menu.Template>
<ControlTemplate>
<Grid Name="ContentGrid"
Width="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Width}"
IsItemsHost="True">
<Grid.ColumnDefinitions>
<ColumnDefinition x:Name="HamburgerButtonColumn" Width="5*" />
<ColumnDefinition x:Name="ButtonsColumn" Width="90*" />
<ColumnDefinition x:Name="RefreshButtonColumn" Width="5*"/>
</Grid.ColumnDefinitions>
<MenuItem Foreground="{DynamicResource BlackBrush}"
Focusable="False"
Template="{DynamicResource MainMenuButtonTemplate}">
<MenuItem.Icon>
<iconPacks:PackIconMaterial Kind="Menu"
HorizontalAlignment="Left"
VerticalAlignment="Center"
MinHeight="20" />
</MenuItem.Icon>
</MenuItem>
<UniformGrid Name="ButtonsUniformGrid"
Grid.Column="1"
Columns="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:AMTMenu}}, Path=ButtonCount}"
Rows="1"
HorizontalAlignment="Stretch">
<MenuItem Grid.Column="0"
Template="{DynamicResource OiButtonsTemplate}"
Foreground="{Binding RelativeSource={RelativeSource Self}, Path=Tag, Converter={StaticResource OiMainMenuButtonsColorBrushConverter}}"
Focusable="False"
Command="{Binding ShowRefreshDataCommand}"
CommandParameter="Button1">
<MenuItem.Tag>
<MultiBinding Converter="{StaticResource MainMenuButtonsTextConverter}" ConverterParameter="INC">
[ ... MultiBinding logic ... ]
</MultiBinding>
</MenuItem.Tag>
</MenuItem>
[ ... XAML Code for the other 4 MenuItems ... ]
</UniformGrid>
<DockPanel Name="PART_Refresh"
Grid.Column="2"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
[ ... XAML Code for the refresh button ... ]
</DockPanel>
</Grid>
</ControlTemplate>
</Menu.Template>
As for the hamburger MenuItem, I have the following template:
<ControlTemplate x:Key="MainMenuButtonTemplate"
TargetType="{x:Type MenuItem}">
<Grid SnapsToDevicePixels="true"
HorizontalAlignment="Stretch">
<StackPanel Background="{TemplateBinding Background}"
VerticalAlignment="Center"
HorizontalAlignment="Center">
<ContentControl x:Name="PART_Button"
Foreground="{TemplateBinding Foreground}"
Background="{TemplateBinding Background}"
Content="{TemplateBinding Icon}"
Focusable="False" />
</StackPanel>
<Popup x:Name="PART_Popup"
AllowsTransparency="true"
Focusable="false"
HorizontalOffset="1"
IsOpen="{Binding IsSubmenuOpen, RelativeSource={RelativeSource TemplatedParent}}"
PopupAnimation="{DynamicResource {x:Static SystemParameters.MenuPopupAnimationKey}}"
Placement="Bottom"
VerticalOffset="-1">
<Border BorderThickness="2"
BorderBrush="White"
Background="{TemplateBinding Background}">
<ScrollViewer x:Name="SubMenuScrollViewer"
CanContentScroll="true"
Style="{DynamicResource {ComponentResourceKey ResourceId=MenuScrollViewer, TypeInTargetAssembly={x:Type FrameworkElement}}}">
<Grid RenderOptions.ClearTypeHint="Enabled">
<ItemsPresenter x:Name="ItemsPresenter"
KeyboardNavigation.DirectionalNavigation="Cycle"
Grid.IsSharedSizeScope="true"
Margin="2"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
KeyboardNavigation.TabNavigation="Cycle"/>
</Grid>
</ScrollViewer>
</Border>
</Popup>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Foreground" Value="{DynamicResource AccentColorBrush}" TargetName="PART_Button"/>
<Setter Property="Background" Value="{DynamicResource GrayBrush}" TargetName="PART_Button"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
Finally, I'm declaring the Menu and submenu with the following XAML:
<local:AMTMenu x:Name="MainMenu"
DockPanel.Dock="Top"
DataContext="{Binding CurrentModel}"
IsButton1Visible="True"
IsButton2Visible="True"
IsButton3Visible="True"
IsButton4Visible="True"
IsButton5Visible="False">
<MenuItem Header="Item 1" />
<Separator />
<MenuItem Header="Item 2" />
<Separator />
<MenuItem Header="Item 3" />
</local:AMTMenu>
How can I bind the Items collection on the Menu to be shown on the hamburger MenuItem popup?
So I found the problem, posting here to help anyone who has a similar problem... The issue was that the hamburger MenuItem was declared on the template so, the Menu wasn't getting any children and consequentely not firing the IsSubmenuOpen property on the MenuItem. After I realized this, the solution was pretty simple, replaced the MenuItem on the Template with an ItemsPresenter and moved the MenuItem to the Menu content. Also, and since the Menu now has Items defined in its class, I can't declare the sub menu as I was doing previously, it would only replace my default item, so I had to use a new DependencyProperty called SubMenuItems.
Here's the final code:
AMTMenu.xaml
<Menu>
<Menu.Template>
<ControlTemplate>
<Grid Name="ContentGrid"
Width="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Width}"
IsItemsHost="True">
<Grid.ColumnDefinitions>
<ColumnDefinition x:Name="HamburgerButtonColumn" Width="5*" />
<ColumnDefinition x:Name="ButtonsColumn" Width="90*" />
<ColumnDefinition x:Name="RefreshButtonColumn" Width="5*"/>
</Grid.ColumnDefinitions>
<ItemsPresenter x:Name="ItemsPresenter"
HorizontalAlignment="Center"
VerticalAlignment="Center"
KeyboardNavigation.DirectionalNavigation="Cycle"
Grid.IsSharedSizeScope="true"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
KeyboardNavigation.TabNavigation="Cycle" />
<UniformGrid Name="ButtonsUniformGrid"
Grid.Column="1"
Columns="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:AMTMenu}}, Path=ButtonCount}"
Rows="1"
HorizontalAlignment="Stretch">
<MenuItem Grid.Column="0"
Template="{DynamicResource OiButtonsTemplate}"
Foreground="{Binding RelativeSource={RelativeSource Self}, Path=Tag, Converter={StaticResource OiMainMenuButtonsColorBrushConverter}}"
Focusable="False"
Command="{Binding ShowRefreshDataCommand}"
CommandParameter="Button1">
<MenuItem.Tag>
<MultiBinding Converter="{StaticResource MainMenuButtonsTextConverter}" ConverterParameter="INC">
[ ... MultiBinding logic ... ]
</MultiBinding>
</MenuItem.Tag>
</MenuItem>
[ ... XAML Code for the other 4 MenuItems ... ]
</UniformGrid>
<DockPanel Name="PART_Refresh"
Grid.Column="2"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
[ ... XAML Code for the refresh button ... ]
</DockPanel>
</Grid>
</ControlTemplate>
</Menu.Template>
<MenuItem Foreground="{DynamicResource BlackBrush}"
Focusable="False"
Template="{DynamicResource MainMenuButtonTemplate}"
AllowDrop="True"
ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=local:AMTMenu}, Path=SubMenuItems}">
<MenuItem.Icon>
<iconPacks:PackIconMaterial Kind="Menu" MinHeight="20" />
</MenuItem.Icon>
</MenuItem>
</Menu>
Menu declaration on parent View:
<local:AMTMenu x:Name="MainMenu"
DockPanel.Dock="Top"
DataContext="{Binding CurrentModel}"
IsButton1Visible="True"
IsButton2Visible="True"
IsButton3Visible="True"
IsButton4Visible="True"
IsButton5Visible="False">
<local:AMTMenu.SubMenuItems>
<local:SubMenuItemsCollection>
<MenuItem Header="Item 1" />
<Separator />
<MenuItem Header="Item 2" />
<Separator />
<MenuItem Header="Item 3" />
</local:SubMenuItemsCollection>
</local:AMTMenu.SubMenuItems>
</local:AMTMenu>
Where SubMenuItemsCollection is just a class that derives from ObservableCollection
public class SubMenuItemsCollection : ObservableCollection<FrameworkElement> { }
Hope this helps someone in the future ;)

Gridsplitter unwanted behavior

It is my first time working with a GridSplitter in WPF. I am trying to allow the user to resize the grid that contains 2 main controls. On top is a datagrid, below is a button with a map image over it. This is what it looks like in the designer. I have a separate row just for the gridsplitter. The xaml for the row definitions is
<Grid.RowDefinitions>
<RowDefinition Height="37" />
<RowDefinition Height="274*" />
<RowDefinition Height="13*"/>
<RowDefinition Height="272*"/>
<RowDefinition Height="4*"/>
</Grid.RowDefinitions>
Interestingly, the GridSplitter seems to work if I'm moving it down. Then I can move it as needed and functions correctly. However, it seems that if I move the splitter above where the line for the row defined above it is, I am unable to move it down again. I can only continue to move it further up.
I have attached a link to a gif showing the behavior that I talk about here.
I am wondering how to go about making the GridSplitter function the same when moving it up or down, as right now, the functionality is correct only if it is moved down from it's initial starting position.
Any help is appreciated.
Update: Here is the full xaml for the user control holding the grid:
<UserControl x:Class="LWDCM.Views.JobsControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:LWDCM.Views"
xmlns:Properties="clr-namespace:LWDCM.Properties"
xmlns:Utility="clr-namespace:LWDCM.Utility"
xmlns:Styles="clr-namespace:LWDCM.Styles"
xmlns:gif="https://github.com/XamlAnimatedGif/XamlAnimatedGif"
xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
xmlns:Converters="clr-namespace:LWDCM.Converters"
mc:Ignorable="d"
Name="jobsControl"
MinWidth="800"
MinHeight="600"
>
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="../Styles/AppStyles.xaml" />
<!-- MahApps.Metro resource dictionaries. Make sure that all file names are Case Sensitive! -->
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colors.xaml" />
<!-- Accent and AppTheme setting -->
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Blue.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
<Grid x:Name="MainGrid"
Margin="0,0,0,0"
Background="#26598c"
>
<!--<Grid.Background>
<LinearGradientBrush ColorInterpolationMode="SRgbLinearInterpolation"
StartPoint="0.5, 0.0"
EndPoint="0.5, 1.0">
<GradientStopCollection>
<GradientStop Color="#FF111111"
Offset="0.0" />
<GradientStop Color="#FF333333"
Offset="0.5" />
<GradientStop Color="#FF111111"
Offset="1.0" />
</GradientStopCollection>
</LinearGradientBrush>
</Grid.Background>-->
<Grid.RowDefinitions>
<RowDefinition Height="37" />
<RowDefinition Height="274*" />
<RowDefinition Height="13*"/>
<RowDefinition Height="272*"/>
<RowDefinition Height="4*"/>
</Grid.RowDefinitions>
<Grid.Resources>
<ContextMenu x:Key="ListViewContextMenu">
<MenuItem x:Name="ContextRename"
Header="{x:Static Properties:Resources.RenameJob}"
Command="{Binding RenameJobCommand}" />
<MenuItem x:Name="ContextSetJobsiteAddress"
Header="{x:Static Properties:Resources.SetJobsiteAddress}"
Command="{Binding UpdateJobSiteAddressCommand}" />
<MenuItem x:Name="ContextSetCustomerAddress"
Header="{x:Static Properties:Resources.SetCustomerAddress}"
Command="{Binding UpdateCustomerInformationCommand}" />
<MenuItem x:Name="ContextSetContractorAddress"
Header="{x:Static Properties:Resources.SetContractorAddress}"
Command="{Binding UpdateContractorInformationCommand}" />
<MenuItem x:Name="ContextEditWorkOrderNumber"
Header="{x:Static Properties:Resources.EditWorkOrderNumber}"
Command="{Binding EditWorkOrderNumberCommand}" />
<Separator/>
<MenuItem x:Name="ExportToKML"
Header="{x:Static Properties:Resources.ExportToKML}"
Command="{Binding ExportToKMLCommand}"/>
</ContextMenu>
<Converters:NullVisibilityConverter x:Key="NullVisibilityConverter" />
</Grid.Resources>
<DataGrid x:Name="JobListView"
AutoGenerateColumns="False"
ItemsSource="{Binding UnitStatusCollection, Mode=TwoWay}"
CanUserDeleteRows="False"
Style="{StaticResource JobGridViewStyle}"
SelectedItem="{Binding JobsListViewSelectedUnitInfo, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Utility:DataGridColumnsBehavior.BindableColumns="{Binding DataGridColumns}"
ContextMenu="{StaticResource ListViewContextMenu}"
Margin="10,0,10,2"
Grid.Row="1"
SelectionMode="Single"
SelectionUnit="FullRow"
HorizontalAlignment="Stretch"
HorizontalContentAlignment="Stretch"
RowStyle="{StaticResource DataGridRowStyle}"
CellStyle="{StaticResource DataGridCellStyle}"
AlternationCount="2"
CanUserResizeRows="False"
HorizontalGridLinesBrush="#d6d6d6"
VerticalGridLinesBrush="#d6d6d6"
Background="#EAEAEA"
>
<!--This is to allow double clicks to open a job in LWD 3x-->
<DataGrid.InputBindings>
<MouseBinding Gesture="LeftDoubleClick"
Command="{Binding OpenInLWD3xCommand}" />
<KeyBinding Key="Return"
Command="{Binding OpenInLWD3xCommand}" />
<KeyBinding Key="F5"
Command="{Binding RefreshCommand}"/>
</DataGrid.InputBindings>
<DataGrid.Resources>
<Converters:DoubleNanVisibilityConverter x:Key="DoubleNanVisibilityConverter" />
<Converters:NullVisibilityConverter x:Key="NullVisibilityConverter" />
</DataGrid.Resources>
</DataGrid>
<Button Cursor="Hand"
Grid.ZIndex="0"
Margin="10,2,10,1"
Grid.Row="3"
x:Name="cmdMapImage"
Visibility="{Binding JobsListViewSelectedUnitInfo, Converter={StaticResource NullVisibilityConverter}}"
Style="{StaticResource MapButtonStyle}"
Command="{Binding ShowMapOnlineCommand}">
<Image x:Name="mapImage"
Source="{Binding DisplayedImage}"
Tag="{Binding JobId}"
Stretch="Fill"
VerticalAlignment="Center"
RenderOptions.BitmapScalingMode="HighQuality">
</Image>
</Button>
<Rectangle Fill="#26598c"
Grid.ZIndex="1"
Margin="0,10,7,0"
Grid.Row="3"
Height="46"
VerticalAlignment="Top"
HorizontalAlignment="Right"
Width="226"
RadiusY="3.667"
RadiusX="3.667"
Focusable="False"/>
<Button Grid.ZIndex="2"
Command="{Binding ScanForwardCommand}"
x:Name="scrollRightButton"
Margin="0,20,15,0"
HorizontalAlignment="Right"
Width="30"
Height="26"
VerticalAlignment="Top"
Grid.Row="3">
<Image x:Name="scrollRight"
Source="/Assets/Down-30px-tall.png"
Stretch="Fill"
VerticalAlignment="Center"
RenderOptions.BitmapScalingMode="HighQuality">
</Image>
</Button>
<Button Grid.ZIndex="2"
Command="{Binding ScanBackwardCommand}"
x:Name="scrollLeftButton"
Margin="0,20,50,0"
RenderTransformOrigin="1,-0.617"
HorizontalAlignment="Right"
Width="30"
Height="26"
VerticalAlignment="Top"
Grid.Row="3">
<Image x:Name="scrollLeft"
Source="/Assets/Up-30px-tall.png"
Stretch="Fill"
VerticalAlignment="Center"
RenderOptions.BitmapScalingMode="HighQuality">
</Image>
</Button>
<ComboBox x:Name="ScanSizesComboBox"
Grid.ZIndex="2"
ItemsSource="{Binding ScanSizes}"
SelectedItem="{Binding SelectedScanSize, Mode=TwoWay}"
ToolTip="{Binding (Validation.Errors)[0].ErrorContent}"
Margin="0,20,85,0"
HorizontalAlignment="Right"
Width="61"
Height="26"
VerticalAlignment="Top"
Grid.Row="3" />
<Button x:Name="OpenLWD"
Grid.ZIndex="2"
Command="{Binding OpenInLWD3xCommand}"
Margin="0,20,150,0"
HorizontalAlignment="Right"
Width="75"
Height="26"
VerticalAlignment="Top"
Grid.Row="3"
Padding="0"
Background="#26598c">
<Image x:Name="openIn3x"
Source="/Assets/LWD-button.png"
Tag="{Binding JobId}"
Stretch="Fill"
VerticalAlignment="Center"
RenderOptions.BitmapScalingMode="HighQuality"
Height="27">
</Image>
</Button>
<DockPanel Grid.Row="0"
LastChildFill="False"
Grid.RowSpan="4">
<Menu x:Name="menu"
DockPanel.Dock="Top"
IsTabStop="False"
FontSize="13"
VerticalAlignment="Top"
Background="WhiteSmoke"
Height="27">
<MenuItem x:Name="FileMenu"
Header="{x:Static Properties:Resources.File}"
Background="Transparent" FontFamily="Arial">
<MenuItem x:Name="BluetoothUpload"
Header="{x:Static Properties:Resources.UploadBluetoothJob}"
IsEnabled="True"
Command="{Binding OpenLWD3xBluetoothCommand}" />
<MenuItem x:Name="FileUpload"
Header="{x:Static Properties:Resources.UploadLocalFile}"
IsEnabled="True"
Command="{Binding AddLocalJobCommand}" />
<Separator />
<MenuItem x:Name="FileLogout"
Header="{x:Static Properties:Resources.Logout}"
IsEnabled="True"
Command="{Binding LogoutCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" />
</MenuItem>
<MenuItem x:Name="ViewMenu"
Header="{x:Static Properties:Resources.View}"
Background="Transparent">
<MenuItem x:Name="ColumnOptions"
Header="{x:Static Properties:Resources.ColumnOptions}"
Background="Transparent"
Command="{Binding ShowColumnOptionsDialogCommand}" />
<MenuItem x:Name="DisplayUnits"
Header="{x:Static Properties:Resources.DisplayUnits}"
Background="Transparent"
Command="{Binding ShowUnitsSelectionCommand}" />
<Separator />
<MenuItem x:Name="ViewRefresh"
IsEnabled="True"
Header="Re_fresh"
Command="{Binding RefreshCommand}"
/>
<!--<MenuItem x:Name="ViewOptions" Header="_Options" />-->
</MenuItem>
<MenuItem x:Name="HelpMenu"
Header="{x:Static Properties:Resources.Help}"
Background="Transparent">
<MenuItem x:Name="HelpOpen"
Header="{x:Static Properties:Resources.OnlineHelp}" />
<Separator />
<MenuItem x:Name="HelpAbout"
Header="{x:Static Properties:Resources.About}"
Command="{Binding ShowAboutDialogCommand}" />
<MenuItem x:Name="DeleteUnits"
Header="Delete all Units"
Command="{Binding RemoveUnitsCommand}"/>
</MenuItem>
</Menu>
</DockPanel>
<GridSplitter x:Name="gridSplitter" Grid.Row="2" Width="Auto" MinHeight="5" MaxHeight="5" HorizontalAlignment="Stretch" VerticalAlignment="Center" Margin="0,4,0,4" />
</Grid>
</UserControl>
And here is the JobGridViewStyle:
<Style x:Key="JobGridViewStyle" TargetType="DataGrid">
<Setter Property="HorizontalAlignment" Value="Stretch" />
<Setter Property="HorizontalContentAlignment" Value="Left" />
<Setter Property="Background" Value="WhiteSmoke" />
<Setter Property="SelectionMode" Value="Single" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Margin" Value="10,0,10,0" />
</Style>
I appreciate the help. I'm really not sure why, but the solution to my answer was to add
ShowsPreview="True"
to my GridSplitter. I have no idea why this would affect the functionality, but it fixed my issue.
For reference, I was looking at this page: How to: Resize Rows with a GridSplitter when I found out the solution.
Thanks again

Menuitem to cut part of the text

The text that is in the MenuItem Header is getting a hidden part, as shown in the image below. The full text is "Informações de Pagamento", but the rest is hidden. I need this component to be this size, width =240
My axml file:
<Image.ContextMenu>
<ContextMenu HorizontalAlignment="Left" Width="240">
<MenuItem x:Name="infoPagamento" Header="_Informações de Pagamento" Cursor="Hand" ToolTip="Online" Click="statusOn_Click" Background="White" Margin="5" >
<MenuItem.Icon>
<Image Source="../Imagens/icons/menuusuario/icon_financeiro.png" />
</MenuItem.Icon>
</MenuItem>
<MenuItem x:Name="alteracaoPlano" Header="Alteração de plano" Cursor="Hand" ToolTip="Alteração de plano" Click="statusAusente_Click" Background="White" Margin="5">
<MenuItem.Icon>
<Image Source="../Imagens/icons/menuusuario/icon_tarefa.png" />
</MenuItem.Icon>
</MenuItem>
<MenuItem x:Name="Relatorios" Header="Relatórios" Cursor="Hand" ToolTip="Ocupado" Click="statusOcupado_Click" Background="White" Margin="5">
<MenuItem.Icon>
<Image Source="../Imagens/icons/menuusuario/icon_relatorios.png" VerticalAlignment="Center" HorizontalAlignment="Center"/>
</MenuItem.Icon>
</MenuItem>
<MenuItem x:Name="Ajuda" Header="Ajuda" Cursor="Hand" ToolTip="Offline" Click="statusOff_Click" Background="White" Margin="5">
<MenuItem.Icon>
<Grid>
<Ellipse Width="20" Height="20" Fill="#48026E" />
<Label Content="?" Padding="0"
VerticalAlignment="Center" HorizontalAlignment="Center"
Foreground="White" FontSize="14" Cursor="Hand"/>
</Grid>
</MenuItem.Icon>
</MenuItem>
</ContextMenu>
</Image.ContextMenu>
My Resource:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style TargetType="{x:Type ContextMenu}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ContextMenu}">
<Border x:Name="Border"
Background="White"
BorderThickness="1" BorderBrush="Transparent"
Margin="3" CornerRadius="10">
<StackPanel IsItemsHost="True"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
I had similar problem for Menu with drop down style. The problem is in reserved space for shortcut like CTRL+D (input gesture text). To overcome limitation I had to set menu item width to fixed size, override menuitem header with text block, set its width to auto (fixed width did not work like expected) and set negative margin for textblock (its size can be different for your problem).
Some short example:
<Menu IsMainMenu="True" Height="auto" Width="220" Margin="0" VerticalAlignment="Center" VerticalContentAlignment="Stretch" HorizontalAlignment="Center" HorizontalContentAlignment="Stretch">
<MenuItem BorderThickness="0" Width="220" Margin="0" VerticalAlignment="Center" VerticalContentAlignment="Stretch" HorizontalAlignment="Left" HorizontalContentAlignment="Stretch">
<MenuItem.Icon>
<Ellipse Width="25" Height="25" HorizontalAlignment="Center" Stretch="Uniform">
<Ellipse.Fill>
<ImageBrush x:Name="imgAvatar" ImageSource="..." TileMode="Tile" Stretch="UniformToFill" />
</Ellipse.Fill>
</Ellipse>
</MenuItem.Icon>
<MenuItem.Header>
<TextBlock Text="Some long long text" Width="auto" TextWrapping="Wrap" Margin="0,0,-75,0" VerticalAlignment="Center" TextAlignment="Left" HorizontalAlignment="Left"/>
</MenuItem.Header>
<MenuItem BorderThickness="0" Width="220" Margin="0" VerticalAlignment="Center" VerticalContentAlignment="Stretch" HorizontalAlignment="Left" HorizontalContentAlignment="Stretch">
<MenuItem.Icon>
<Ellipse Width="25" Height="25" HorizontalAlignment="Center" Stretch="Uniform">
<Ellipse.Fill>
<ImageBrush x:Name="imgAvatar" ImageSource="..." TileMode="Tile" Stretch="UniformToFill" />
</Ellipse.Fill>
</Ellipse>
</MenuItem.Icon>
<MenuItem.Header>
<TextBlock Text="Some long long text 2" Width="auto" TextWrapping="Wrap" Margin="0,0,-75,0" VerticalAlignment="Center" TextAlignment="Left" HorizontalAlignment="Left"/>
</MenuItem.Header>
</MenuItem>
</MenuItem>
</Menu>
Try setting the width of MenuItem as "Auto"

Draw text on WriteableBitmap

I would like to draw some text on a WriteableBitmap. This doesn't seem possible, but I found converting WriteableBitmap to Bitmap in C# here and this.
Here's the call (with conversion method included, too):
// Draw dino names...
Graphics g = Graphics.FromImage(BitmapFromWriteableBitmap(writeableBitmap));
g.DrawString(Dinosaurs[i].PersonalName, new Font("Tahoma", 40), System.Drawing.Brushes.White, new PointF((float)Dinosaurs[i].Head.X, (float)Dinosaurs[i].Head.Y));
} // for i
}// DrawDinos2d
private System.Drawing.Bitmap BitmapFromWriteableBitmap(WriteableBitmap writeBmp)
{
System.Drawing.Bitmap bmp;
using (MemoryStream outStream = new MemoryStream())
{
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create((BitmapSource)writeBmp));
enc.Save(outStream);
bmp = new System.Drawing.Bitmap(outStream);
}
return bmp;
}
I've checked in the debugger and g has a good values (not null) but nothing is drawing on the screen. I should also mention that the string that is being passed to DrawString is good and the X,Y of the point is good (positive integers about 1000,800). I think it's either drawing off the screen or maybe the X,Y coordinates aren't translating correctly.
Any ideas? Thanks.
Here's the XAML (if this helps):
<Window x:Class="DinosaurIsland.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Dinosaur Island" Height="600" Width="600" WindowState="Normal" Icon="/DinosaurIsland;component/Icon1.ico" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" WindowStartupLocation="CenterOwner">
<Window.Resources>
<ResourceDictionary>
<DataTemplate DataType="{x:Type BitmapImage}">
<Image Source="{Binding}" />
</DataTemplate>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Resources.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<DockPanel>
<Menu x:Name="MainMenu" DockPanel.Dock="Top">
<MenuItem Header="_File">
<MenuItem Header="_Open Dinosaur Island 'snapshot' file..." x:Name="OpenSnapshotFile" Click="OpenSnapshotFile_click" />
<MenuItem Header="_Save"/>
<MenuItem Header="_Exit" x:Name="ExitApp" Click="ExitAppClick" />
</MenuItem>
<MenuItem Header="_Height Map">
<MenuItem Header="Load Height Map..." Name="LoadHeightMap" Click="LoadHeightMapClick" />
<Separator />
<MenuItem Header="Display Height Map" x:Name="DisplayHeightMap" Click="DisplayHeightMapClick" />
</MenuItem>
<MenuItem Header="Terrain">
<MenuItem Header="Load Terrain Map..." x:Name="LoadTerrainMap" Click="LoadTerrainMap_Click" />
<MenuItem Header="Draw Terrain..." x:Name="DrawTerrain" Click="DisplayTerrainPaintBoxClick" />
<MenuItem Header="Save Terrain Map..." x:Name="SaveTerrainMap" Click="SaveTerrainMap_Click"/>
<MenuItem Header="Get Terrain Data From BMP..." x:Name="TerrainFromBMP" Click="TerrainFromBMP_Click" />
<Separator />
<MenuItem Header="Adjust Terrain Transparency..." x:Name="AdjustTerrainTransparency" Click="AdjustTerrainTransparency_Click"/>
<MenuItem Header="Display Terrain Map" x:Name="DisplayTerrainMap" Click="DisplayTerrainMap_Click"/>
</MenuItem>
<MenuItem Header="_Vegetation">
<MenuItem Header="Plant Vegetation..." x:Name="PlantVegetation" Click="PlantVegetation_Click" />
<Separator />
<MenuItem Header="Load Vegetation Map..." x:Name="LoadVegetation" Click="LoadVegetation_Click" />
<MenuItem Header="Save Vegetation Map..." x:Name="SaveVegetation" Click="SaveVegetation_Click" />
<Separator />
<MenuItem Header="Display Vegetation" Click="DisplayVegetation_Click" />
</MenuItem>
<MenuItem Header="Dinosaurs">
<MenuItem Header="Edit / Place Dinosaurs..." x:Name="EditDinosaurs" Click="EditDinosaurs_Click" />
<Separator />
<MenuItem Header="Load Dinosaur Map" Name="LoadDinosaurnMap" Click="LoadDinosaurs_Click"/>
<MenuItem Header="Save Dinosaur Map" Name="SaveDinosaurMap" Click="SaveDinosaurs_Click"/>
<Separator />
<MenuItem Header="Terrain/Slope Effect..." Name="TerrainSlope" Click="TerrainSlope_Click"/>
<MenuItem Header="Probability of Smelling Dinosaur..." Name="SmellProbability" Click="SmellProbability_Click"/>
</MenuItem>
<MenuItem Header="Time">
<MenuItem Header="Start..." x:Name="AdvanceTime" Click="StartTime_Click" />
<MenuItem Header="Stop..." x:Name="StopTime" Click="StopTime_Click" />
<Separator />
<MenuItem Header="Adjust Time Step..." x:Name="AdjustTimeStep" Click="AdjustTimeStep_Click"/>
</MenuItem>
<MenuItem Header="Debug">
<MenuItem Header="A* trace" Name="AStarTrace" Click="AStarTrace_Click" />
<MenuItem Header="Show Dinosaur Goals" Name="DinoGoals" Click="DinoGoals_Click" />
<MenuItem Header="Show Dinosaur Path" Name="DinoPath" IsChecked="False" Click="DinoPath_Click" />
<MenuItem Header="Show Predator Scent Path" Name="StinkPath" IsChecked="False" Click="StinkPath_Click" />
<MenuItem Header="Show Dinosaur Vision Angles" Name="VisionAngles" IsChecked="True" Click="VisionAngles_Click" />
<MenuItem Header="Show Dinosaur Axis" Name="DinoAxis" IsChecked="True" Click="DinoAxis_Click" />
</MenuItem>
<MenuItem Header="Help">
<MenuItem Header="About Dinosaur Island" Name="AboutDinosaurIsland" Click="AboutDinoIslandClick" />
</MenuItem>
</Menu>
<StatusBar DockPanel.Dock="Bottom">
<TextBlock Name="StatusBarField1">Location = X,Y</TextBlock>
<Separator/>
<TextBlock Name="StatusBarField2">Elevation = X</TextBlock>
<Separator/>
<TextBlock Name="StatusBarField3">Terrain = None</TextBlock>
<Separator/>
<TextBlock Name="StatusBarField4">Plants = None</TextBlock>
<Separator/>
<TextBlock Name="StatusBarField5">Dinosaurs = None</TextBlock>
<Separator/>
<TextBlock Name="StatusBarField6">Zoom</TextBlock>
<Separator/>
<TextBlock Name="StatusBarField7">Time 0:00</TextBlock>
<Separator/>
<TextBlock Name="StatusBarField8">Wind direction: 000</TextBlock>
<Separator/>
<TextBlock Name="StatusBarField9">Speed: 000</TextBlock>
</StatusBar>
<Label DockPanel.Dock="Bottom" Content="Scale = 2000 meters" Height="23" HorizontalAlignment="Center" Name="HorizScaleDisplayText" Width="127" />
<Label DockPanel.Dock="Bottom" Content="└───────────────────────────────┴───────────────────────────────────┘" Height="20" HorizontalAlignment="Center" Name="HorizScaleDisplayLine" Width="423" />
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Slider Grid.Column="0" Orientation="Vertical" HorizontalAlignment="Left" Minimum="1" x:Name="slider"/>
<ScrollViewer Name="scrollViewer" Grid.Column="1" VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Visible" Margin="0,0,0,6">
<Grid Name="grid" Width="400" Height="400" RenderTransformOrigin="0.5,0.5">
<Grid.RowDefinitions>
<RowDefinition Height="37*" />
<RowDefinition Height="363*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="297*" />
<ColumnDefinition Width="103*" />
</Grid.ColumnDefinitions>
<Grid.LayoutTransform>
<TransformGroup>
<ScaleTransform x:Name="scaleTransform"/>
</TransformGroup>
</Grid.LayoutTransform>
<Viewbox x:Name="viewBox" Margin="-35,-12,-22,22" Grid.ColumnSpan="2" Grid.RowSpan="2">
<ContentPresenter x:Name="contentPresenter" Width="350" Height="350" >
<ContentPresenter.Content>
<Image x:Name="image" Width="350" Height="350">
<Image.Source >
<BitmapImage x:Name="HeightMapImage" UriSource="DinoIslandLogo.bmp" />
</Image.Source>
</Image>
</ContentPresenter.Content>
</ContentPresenter>
</Viewbox>
</Grid>
</ScrollViewer>
</Grid>
</DockPanel>
And this is how I display the bitmap:
this.image.Source = writeableBitmap;
This solved the problem:
public void DrawDinoNames()
{
System.Drawing.Bitmap bmp;
bmp = BitmapFromWriteableBitmap(writeableBitmap);
Graphics g = Graphics.FromImage(bmp);
for (int i = 0; i < Dinosaurs.Count; i++)
{
g.DrawString(Dinosaurs[i].PersonalName, new Font("Tahoma", 14), System.Drawing.Brushes.White, new PointF((float)Dinosaurs[i].Head.X, (float)Dinosaurs[i].Head.Y));
}
this.image.Source = BitmapToImageSource(bmp, System.Drawing.Imaging.ImageFormat.Bmp);
}

Categories

Resources