I have a template for a DataGrid located in a ResourceDictionary.
BlockStyles.xaml
<Style TargetType="DataGrid" x:Key="SearchExpGrid">
<Setter Property="AlternatingRowBackground" Value="#4C87C6ff"/>
<Setter Property="GridLinesVisibility" Value="None"/>
<Setter Property="FontSize" Value="15"/>
<Setter Property="HeadersVisibility" Value="Column"/>
<Setter Property="CellStyle">
<Setter.Value ... />
</Setter>
<Setter Property="RowStyle">
<Setter.Value ... />
</Setter>
<Setter Property="ColumnHeaderStyle">
<Setter.Value>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Border
x:Name="Border" Background="White" BorderBrush="#4C87C6" BorderThickness="1" >
<StackPanel Orientation="Horizontal" Margin="5,5" HorizontalAlignment="Center">
<TextBlock
x:Name="TxtB" Text="{Binding}"
Foreground="#4C87C6" FontWeight="DemiBold" HorizontalAlignment="Center"/>
<Image Source="../Images/dropdown.png"
Width="10" Height="10" Margin="5,0,5,0"
MouseEnter="DropdownButton_MouseEnter"
MouseLeave="DropdownButton_MouseLeave"
MouseEnter="DropdownButton_Click"/>
</StackPanel>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="Border" Property="Background" Value="#4C87C6"/>
<Setter TargetName="TxtB" Property="Foreground" Value="White"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Setter.Value>
</Setter>
</Style>
I always have an error because the function can't find it's definition.
I first implemented the function in the View file where the style is used but it doesn't work.
I tried this method from StackOverflow using a resource class inheriting ResourceDictionnary but got the same error.
I then tried to use ICommand and RelayCommand to execute the function from the ViewModel but didn't got any result.
I also didn't find where I could add an EventHandler ImgDropdownButton.MouseEnter += new MouseEventHandler(MouseEnter_DropdownButton); using MVVM.
Is there a better solution for this kind of behaviour or if adding an EventHandler is the best solution, where sould be the best place to add it ?
Thanks in advance
Edit :
I managed to handle the function using a code-behind file for my ResourceDictionary following this.
BlockStyles.xaml.cs
private void DropdownButton_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
{
Mouse.OverrideCursor = Cursors.Hand;
}
private void DropdownButton_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
{
Mouse.OverrideCursor = Cursors.Arrow;
}
private void DropdownButton_Click(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
//Function to show the popup
}
The MouseEnter and MouseLeave function are working, but I don't understand how to use the function to make my popup appear.
What I'm trying to do is that when I click on the Dropdown Image on the column header, I want to display a Popup, like an Excel one. This will allow the user to filter the columns values.
The file where my Grid and Popup are : (SearchExpView.xaml)
<Grid Grid.Row="2" Grid.Column="1">
<searchcomponents:ExpListView x:Name="ExpDatagrid"
DataContext="{Binding OExpListVM}"
Width="auto" Height="auto"/>
</Grid>
<Popup x:Name="PopupFiltre">
PopupFiltre content
</Popup>
Definition of my Datagrid : (ExpListView.xaml)
<Grid>
<DataGrid x:Name="ExpGrid" Style="{StaticResource SearchExpGrid}"
BorderThickness="0" BorderBrush="#4C87C6"
HorizontalAlignment="Left" VerticalAlignment="Top"
MinHeight="200" Height="auto" Margin="10,10,0,0"
MinWidth="780" Width="auto"
ItemsSource="{Binding}" DataContext="{Binding tableExpertise.DefaultView}"
AutoGenerateColumns="True" CanUserAddRows="False" IsReadOnly="True">
<DataGrid.InputBindings>
<MouseBinding MouseAction="LeftDoubleClick"
Command="{Binding DataContext.OnRowDoubleClickedCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"
CommandParameter="{Binding ElementName=ExpGrid, Path=CurrentItem}"/>
</DataGrid.InputBindings>
<DataGrid.ContextMenu>
<ContextMenu Name="dgctxmenu">
<Separator></Separator>
</ContextMenu>
</DataGrid.ContextMenu>
</DataGrid>
</Grid>
I'm looking for a way to be able to implement this popup fonction but I can't find out how to link everything together.
My Window is SearchExpView.xaml (with the Datagrid and the Popup). My Datagrid component is defined in ExpListView.xaml and styled in BlockStyles.xaml, which is not a window. I want to make the Popup (in SearchExpView.xaml) visible by clicking on the dropdown button (defined in BlockStyles.xaml)
Then you need to get a reference to the Popup in the window from the ResourceDictionary somehow.
You could for example use the static Application.Current.Windows property:
var window = Application.Current.Windows.OfType<SearchExpView>().FirstOrDefault();
if (window != null)
window.PopupFiltre.IsOpen = true;
Also make sure that you make the Popup accessible from outside the SearchExpView class:
<Popup x:Name="PopupFiltre" x:FieldModifier="internal">
...
Related
I have a listbox that loads it's items with Foreground color set to red. What I'd like to do is: upon selecting an item with the mouse, change the foreground color of SelectedItem to black, but make the change persistent so that after deselecting the item, color remains black. Incidentally I want to implement this as a way of showing 'read items' to the user.
Essentially I want something like an implementation of the common property trigger like the code below, but not have the style revert after deselection. I've played around with event triggers as well without much luck.
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True" >
<Setter Property="Foreground" Value="Black" /> //make this persist after deselection
</Trigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
Thanks in advance!
You could animate the Foreground property:
<ListBox>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Foreground" Value="Red" />
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Trigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<ColorAnimation Storyboard.TargetProperty="(ListBoxItem.Foreground).(SolidColorBrush.Color)"
To="Black" />
</Storyboard>
</BeginStoryboard>
</Trigger.EnterActions>
</Trigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
The downside of this simple approach is that the information is not stored somewhere. This is pure visualization without any data backing. In order to persist the information, so that restarting the application shows the same previous state, you should introduce a dedicated property to your data model e.g IsMarkedAsRead.
Depending on your requirements, you can override the ListBoxItem.Template and bind ToggleButton.IsChecked to IsMarkedAsRead or use a Button which uses a ICommand to set the IsMarkedAsRead property. There are many solutions e.g. implementing an Attached Behavior.
The following examples overrides the ListBoxItem.Template to turn the ListBoxItem into a Button. Now when the item is clicked the IsMarkedAsRead property of the data model is set to true:
Data model
(See Microsoft Docs: Patterns - WPF Apps With The Model-View-ViewModel Design Pattern for an implementation example of the RelayCommand.)
public class Notification : INotifyPropertyChanged
{
public string Text { get; set; }
public ICommand MarkAsReadCommand => new RelayCommand(() => this.IsMarkedAsRead = true);
public ICommand MarkAsUnreadCommand => new RelayCommand(() => this.IsMarkedAsRead = false);
private bool isMarkedAsRead;
public bool IsMarkedAsRead
{
get => this.isMarkedAsRead;
set
{
this.isMarkedAsRead = value;
OnPropertyChanged();
}
}
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
ListBox
<ListBox ItemsSource="{Binding Notifications}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border Background="{TemplateBinding Background}">
<Button x:Name="ContentPresenter"
ContentTemplate="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListBox}, Path=ItemTemplate}"
Content="{TemplateBinding Content}"
Command="{Binding MarkAsReadCommand}"
Foreground="Red">
<Button.Template>
<ControlTemplate TargetType="Button">
<Border>
<ContentPresenter />
</Border>
</ControlTemplate>
</Button.Template>
</Button>
</Border>
<ControlTemplate.Triggers>
<DataTrigger Binding="{Binding IsMarkedAsRead}" Value="True">
<Setter TargetName="ContentPresenter" Property="Foreground" Value="Green" />
</DataTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type Notification}">
<TextBlock Text="{Binding Text}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Thanks a lot #BionicCode for the comprehensive answer. I ended up going with another solution which may or may not be good convention; I am a hobbyist.
Firstly, I don't need databacking / persistence.
Concerning the data model solution and overriding ListBoxItem.Template, I am using a prededfined class 'SyndicationItem' as the data class (my app is Rss Reader). To implement your datamodel solution I guess I could hack an unused SyndicationItem property, or use SyndicationItem inheritance for a custom class (I'm guessing this is the most professional way?)
My complete data model is as follows:
ObservableCollection >>> CollectionViewSource >>> ListBox.
Anyway I ended up using some simple code behind which wasn't so simple at the time:
First the XAML:
<Window.Resources>
<CollectionViewSource x:Key="fooCollectionViewSource" Source="{Binding fooObservableCollection}" >
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="PublishDate" Direction="Descending" />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
<Style x:Key="DeselectedTemplate" TargetType="{x:Type ListBoxItem}">
<Setter Property="Foreground" Value="Gray" />
</Style>
</Window.Resources>
<ListBox x:Name="LB1" ItemsSource="{Binding Source={StaticResource fooCollectionViewSource}}" HorizontalContentAlignment="Stretch" Margin="0,0,0,121" ScrollViewer.HorizontalScrollBarVisibility="Disabled" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="80" />
</Grid.ColumnDefinitions>
<TextBlock MouseDown="TextBlock_MouseDown" Grid.Column="0" Text="{Binding Path=Title.Text}" TextWrapping="Wrap" FontWeight="Bold" />
<TextBlock Grid.Column="1" HorizontalAlignment="Right" TextAlignment="Center" FontSize="11" FontWeight="SemiBold"
Text="{Binding Path=PublishDate.LocalDateTime, StringFormat='{}{0:d MMM, HH:mm}'}"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Now the code behind:
Solution 1: this applies a new style when listboxitem is deselected. Not used anymore so the LB1_SelectionChanged event is not present in the XAML.
private void LB1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.RemovedItems.Count != 0)
{
foreach (var lbItem in e.RemovedItems)
{
//get reference to source listbox item. This was a pain.
int intDeselectedItem = LB1.Items.IndexOf(lbItem);
ListBoxItem lbi = (ListBoxItem)LB1.ItemContainerGenerator.ContainerFromIndex(intDeselectedItem);
/*apply style. Initially, instead of applying a style, I used mylistboxitem.Foreground = Brushes.Gray to set the text color.
Howver I noticed that if I scrolled the ListBox to the bottom, the text color would revert to the XAML default style in my XAML.
I assume this is because of refreshes / redraws (whichever the correct term). Applying a new style resolved.*/
Style style = this.FindResource("DeselectedTemplate") as Style;
lbi.Style = style;
}
}
}
Solution 2: The one I went with. Occurs on SelectedItem = true, same effect as your first suggestion.
private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e)
{
TextBlock tb = e.Source as TextBlock;
tb.Foreground = Brushes.Gray;
}
I have a UserControl that is a ListView with a Canvas as the ItemsPanel. The ItemsSource of the ListView is bound to a CollectionViewSource with it's Source property bound to an ObservableCollection< DeviceItem >. DeviceItem is a custom class that, among other things, holds the X/Y coordinates of the ListViewItem/DeviceItem which gets serialized when the user wants to save their work. On PreviewMouseDown and PreviewTouchDown I check the ListViewItem that's being clicked/touched to make sure that the content of the ListViewItem is a DeviceItem so that as the user moved it around the screen the software can updates the coordinates on the DeviceItem. This works 99% of the time but I run into a problem (sometimes) after the user removes items from the collection and then adds new items. After removing/adding, when the user clicks/touches the ListViewItem it's Content is typeof MS.Internal.NamedObject and in that case I can't act on the item. I'm sure it's worth mentioning that the user is adding/removing from a separate control in another window that is bound to the same collection in our data model (ObservableCollection< DeviceItem >).
Currently the user has to close and reopen the software when this happens. I'm trying to find a way to recover without restarting the software.
<UserControl.Resources>
<Style x:Key="CanvasStyle" TargetType="{x:Type Canvas}">
<EventSetter Event="Loaded" Handler="Canvas_Loaded"/>
</Style>
<CollectionViewSource Source="{Binding DiagramCollection}" x:Key="radioPacksDataView" />
</UserControl.Resources>
<Grid>
<ListView Name="listBoxDevices"
Background="Transparent"
BorderThickness="0"
Stylus.IsPressAndHoldEnabled ="False"
ItemsSource="{Binding Source={StaticResource radioPacksDataView}}"
PreviewMouseMove="ListBox_PreviewMouseMove"
PreviewMouseDown="ListBox_PreviewMouseDown"
PreviewMouseUp="ListBox_PreviewMouseUp"
PreviewTouchDown="ListBox_PreviewTouchDown"
PreviewTouchMove="ListBox_PreviewTouchMove"
PreviewTouchUp="ListBox_PreviewTouchUp"
SnapsToDevicePixels="True"
IsHitTestVisible="{Binding AccessRights, ConverterParameter=Unlocked, Converter={StaticResource enumBooleanConverter}, Source={x:Static appData:Globals.CurrentUser}}"
VirtualizingPanel.IsVirtualizing="False"
IsSynchronizedWithCurrentItem="False">
<ListView.Style>
<Style>
<Setter Property="ItemsControl.ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<Canvas Style="{DynamicResource CanvasStyle}"/>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=window, Path=IconStyle}" Value="0">
<Setter Property="ListView.ItemContainerStyle" Value="{DynamicResource MultiDeviceItemContainerStyle}" />
</DataTrigger>
<DataTrigger Binding="{Binding ElementName=window, Path=IconStyle}" Value="1">
<Setter Property="ListView.ItemContainerStyle" Value="{DynamicResource MultiDeviceItemContainerStyleV2}" />
</DataTrigger>
</Style.Triggers>
</Style>
</ListView.Style>
<ListView.LayoutTransform>
<ScaleTransform CenterX="0"
CenterY="0"
ScaleX="{Binding ZoomScale}"
ScaleY="{Binding ZoomScale}"/>
</ListView.LayoutTransform>
</ListView>
</Grid>
And then in code behind
private void ListBox_PreviewMouseDown(object sender, MouseEventArgs e)
{
if (m_selectedListViewItem == null)
{
m_selectedListViewItem = ItemsControl.ContainerFromElement((ListBox)sender, e.OriginalSource as DependencyObject) as ListViewItem;
//this is the section that fails after removing/adding items, object is typeof(MS.Internal.NamedObject)
if (m_selectedListViewItem.Content.GetType().IsSubclassOf(typeof(DeviceItem)))
{
m_selectedDeviceItem = m_selectedListViewItem.Content as DeviceItem;
}
}
}
I create in XAML RadGridVieaw controls custom tooltip and when tool tip before opening, I want read row and take ID and then load picture from database.
1 step I create custom tool tip
<Style TargetType="{x:Type telerik:GridViewRow}" BasedOn="{StaticResource GridViewRowStyle}" >
<Setter Property="ToolTipService.IsEnabled" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type telerik:RadGridView}}}" />
<Setter Property="ToolTip" >
<Setter.Value>
<ToolTip ToolTipService.ShowDuration="1000000" >
<Grid >
<Border HorizontalAlignment="Left" Height="170" Margin="5,0,0,0"
VerticalAlignment="Top" Width="130" BorderBrush="#FFCED8DA" BorderThickness="1" Padding="1">
<Image x:Name="GeneralTabItem_EmployeeImage" Source="{Binding CRAPhotoPhoto, Converter={StaticResource BinaryArrayToURIConverter}}" Stretch="UniformToFill"
Width="120" Height="160"/>
</Border>
<Grid/>
<telerik:RadGridView x:Name="ExtnedPrisonerInfoView_DataInput_ListGrid" HorizontalAlignment="Stretch" Margin="0,0,0,0" VerticalAlignment="Stretch" ToolTipService.ShowDuration="100000000"
DataContext="{Binding ''}" ToolTipOpening="OnContentChanged">
</telerik:RadGridView>
2 step I want to code behind catch event opening Tool tip.
3 step attach picture to the opening tool tip Image in Name="GeneralTabItem_EmployeeImage"
Please help me ToolTipOpening event is not working.
This should work as far as the event handler is concerned:
<Style TargetType="{x:Type telerik:GridViewRow}" BasedOn="{StaticResource GridViewRowStyle}" >
<EventSetter Event="ToolTipOpening" Handler="outerGrid_ToolTipOpening" />
...
But if you want to do something with the Image in the ToolTip, you need to wait until it has been created. You might as well handle the Loaded event of the Image and set the Source of it in there:
private void GeneralTabItem_EmployeeImage_Loaded(object sender, RoutedEventArgs e)
{
Image img = sender as Image;
//set source...
}
XAML:
<Setter Property="ToolTip" >
<Setter.Value>
<ToolTip ToolTipService.ShowDuration="1000000">
<Grid>
<Border HorizontalAlignment="Left" Height="170" Margin="5,0,0,0"
VerticalAlignment="Top" Width="130" BorderBrush="#FFCED8DA" BorderThickness="1" Padding="1">
<Image x:Name="GeneralTabItem_EmployeeImage" Stretch="UniformToFill"
Width="120" Height="160"
Loaded="GeneralTabItem_EmployeeImage_Loaded"/>
</Border>
<Grid/>
</Grid>
</ToolTip>
</Setter.Value>
</Setter>
Obviously you won't be able to set the Source property of an Image that resides in a ToolTip before the ToolTip has been opened because by then there is no Image. So this doesn't make much sense.
Create a simple tooltip first:
<Style TargetType="telerik:GridViewRow" BasedOn="{StaticResource
GridViewRowStyle}">
<Setter Property="ToolTip">
<Setter.Value>
<ToolTip>
<TextBlock Text="{Binding EmployeeName}"></TextBlock>
</ToolTip>
</Setter.Value>
</Setter>
</Style>
Verify that works and if it does start adding more complex things like converters and ToolTipService stuff one at a time to see what is it exactly that is invalidating your XAML because XAML error is the only reason why the event would not be firing...
When a button gets pressed the background (Rectangle Fill) of the button changes. So the user can see what buttons have been pressed and what not.
Problem:
I use a trigger and a Togglebutton to perform the "IsChecked" to change the background.
But the background change may only happens 1 time.
For example:
Button Background = black --> PRESS --> Button Background = blue
But when i press the button again the Button BackGround changes back to black (since its a ToggleButton).
How can i make sure the background only changes 1 time?
EDIT: The button must remain enabled, because a user gives in a reason when they press the button. Meaning if they pick the wrong reason they are able to change it.
<Style x:Key="ButtonStyleReg" TargetType="{x:Type myClasses:RegButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ToggleButton}">
<Grid x:Name="registrationButton">
<Rectangle Name="rectangleBtn" Fill="#FF89959A" Height="Auto" RadiusY="15" RadiusX="15" Stroke="White" Width="Auto"/>
<TextBlock x:Name="reason" TextWrapping="Wrap"
Text="{Binding Reason, StringFormat=\{0\}}"
HorizontalAlignment="Center" Margin="0,7.5,0,0" Height="Auto"
VerticalAlignment="Top" FontWeight="Bold" >
</TextBlock>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsFocused" Value="True"/>
<!--<Trigger Property="IsDefaulted" Value="True"/>-->
<Trigger Property="IsChecked" Value="True">
<Setter TargetName="rectangleBtn" Property="Fill" Value="blue" />
</Trigger>
<Trigger Property="IsEnabled" Value="False"/>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="FontSize" Value="10.667"/>
Listbox that implements the style:
<ListBox x:Name="lbRegistration" ItemsSource="{Binding RegBtns, ElementName=Window}" Background="{x:Null}"
BorderBrush="{x:Null}" Grid.Column="1"
ScrollViewer.HorizontalScrollBarVisibility="Hidden" ScrollViewer.VerticalScrollBarVisibility="Disabled" Height="75">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<myClasses:RegistrationButton x:Name="RegistrationButton" HorizontalAlignment="Center" Height="71" Width="148"
Margin="10,0,5,0"
Style="{DynamicResource ButtonStyleRegistration}"
Click="RegistrationButton_Click"
Title="{Binding Title}"
Oorzaak="{Binding Oorzaak}"
DuurStilstand="{Binding DuurStilstand,
Converter={StaticResource DateTimeConverter}}"
BeginStilstand="{Binding BeginStilstand}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Best Regards,
Pete
Very simple would be if you can access the rectangle from code behind:
rectangleBtn.Fill = Brushes.Blue;
If you can't access it - make yourself two styles.
The one that is the original style, the other one is the Blue Style which shall be applied when the user clicks.
In the code behind, on event Click="RegistrationButton_Click"
Set the Style to the BlueStyle.
RegistrationButton.Style = this.FindResource("ButtonStyleRegistration") as Style;
Since you always want it blue, this code is enough as it is. It will always make it Blue for you.
The first time, and any other time.
That way you achieve your requirement and the style will change only once.
When the window is loaded, it will load into the original style (the first style).
So put in your XAML the style "Black" and in the code behind as shown above.
Then this must be removed:
<Trigger Property="IsChecked" Value="True">
<Setter TargetName="rectangleBtn" Property="Fill" Value="blue" />
</Trigger>
Then this:
<myClasses:RegistrationButton x:Name="RegistrationButton" HorizontalAlignment="Center" Height="71" Width="148"
Margin="10,0,5,0"
Style="{DynamicResource ButtonStyleRegistration}"
Click="RegistrationButton_Click"
Shall be:
<myClasses:RegistrationButton x:Name="RegistrationButton" HorizontalAlignment="Center" Height="71" Width="148"
Margin="10,0,5,0"
Style="{DynamicResource ButtonStyleRegBlack}"
Click="RegistrationButton_Click"
That is all.
If you're using an MVVM approach I would recommend binding the background and the Click command to members in the ViewModel. The first time the button is clicked it sets a flag and changes the background color. The next time the button is clicked, if the flag is set, the command returns without changing the background.
XAML:
<ToggleButton Background="{Binding MyBackground}" Command="{Binding OnClickCmd}"/>
ViewModel
public class ViewModel : INotifyPropertyChanged
{
public Brush MyBackground
{
get { return background_; }
set {
background_ = value;
PropertyChanged(this, new PropertyChangedEventArg("MyBackground");
}
}
public ICommand OnClickCmd
{
get {
return new DelegateCommand(()=>{ // DelegateCommand implements ICommand
if(!isBackgroundSet) {
background = Brushes.Red;
isBackgroundSet_ = true;
}
});
}
}
private Brush background_;
private bool isBackgroundSet_;
private event PropertyChangedEventHandler PropertyChagned;
}
Im getting menuItem icon appearing only on last menuItem.
If i snoop the app only last menuItem has image in icon, while if i debug all MenuItems appear to have image in icon. Also if i add submenuItem the icon on menuItem dissapears once i open submenus and the last submenu gets the icon... Any idea? PS: also tooltips on menu item dont work.
Im using caliburn micro and fluent ribbon controls.
<ControlTemplate x:Key="dropDownButton">
<ef:DropDownButton Header="{Binding DisplayName}"
ItemsSource="{Binding Items}"
LargeIcon="{Binding LargeIconPath}"
cm:Message.Attach="ClickAction()"
ef:KeyTip.Keys="{Binding KeyTip}">
<ef:DropDownButton.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Header"
Value="{Binding DisplayName}"/>
<Setter Property="Icon">
<Setter.Value>
<Image Source="{Binding Path=IconPath}"/>
</Setter.Value>
</Setter>
<Setter Property="ItemsSource"
Value="{Binding Items}"/>
<Setter Property="cm:Message.Attach"
Value="ClickAction()"/>
<Setter Property="ef:KeyTip.Keys"
Value="{Binding KeyTip}"/>
<Setter Property="ToolTip">
<Setter.Value>
<ef:ScreenTip Title="{Binding DisplayName}"
HelpTopic="ScreenTip help ..."
Image="{Binding LargeIconPath}"
Text="Text for ScreenTip"/>
</Setter.Value>
</Setter>
</Style>
</ef:DropDownButton.ItemContainerStyle>
<ef:DropDownButton.ToolTip>
<ef:ScreenTip Title="{Binding DisplayName}"
HelpTopic="ScreenTip help ..."
Image="{Binding LargeIconPath}"
Text="Text for ScreenTip"/>
</ef:DropDownButton.ToolTip>
</ef:DropDownButton>
You are setting Icon property to an Image control in Style. Now, only one copy of Style is created and thus, only one copy of Image is created. Now, any control can have only one parent at a time. So, when it is assigned to last MenuItem, it is removed from previous MenuItem controls. To fix this, use Templates.
Instead of setting Header property, set HeaderTemplate:
<Setter Property="HeaderTemplate">
<Setter.Value>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Image Grid.Column="0"
Source="{Binding Path=IconPath}" />
<TextBlock Grid.Column="1"
Text="{Binding DisplayName}" />
</Grid>
</DataTemplate>
</Setter.Value>
</Setter>
I'm not sure of what properties are exposed by the control toolkit you are using. But, I'm sure they must have a template property.
After doing this, you don't need to set Icon property in style.
I successfully use the following entries in a ResourceDictionary:
<!-- Define non-shared image to avoid loss of menu icons -->
<Image x:Key="MenuIconImage" Height="16" Width="16" x:Shared="false">
<Image.Source>
<DrawingImage Drawing="{Binding Icon}" />
</Image.Source>
</Image>
<Style TargetType="{x:Type MenuItem}" BasedOn="{StaticResource {x:Type MenuItem}}">
<Setter Property="Header" Value="{Binding DisplayName />
<Setter Property="Icon" Value="{StaticResource MenuIconImage}" />
</Style>
Works like this:
<DataTemplate x:Key="MenuItemHeaderTemplate">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Image Grid.Column="0" Source="{Binding Path=IconPath}" />
<Label Grid.Column="1" Content="{Binding DisplayName}" />
</Grid>
</DataTemplate>
<ControlTemplate x:Key="dropDownButton">
<ef:DropDownButton Header="{Binding DisplayName}"
ItemsSource="{Binding Items}"
LargeIcon="{Binding LargeIconPath}"
cm:Message.Attach="ClickAction()"
ef:KeyTip.Keys="{Binding KeyTip}">
<ef:DropDownButton.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="HeaderTemplate" Value="{StaticResource MenuItemHeaderTemplate}" />
<Setter Property="ItemsSource"
Value="{Binding Items}"/>
<Setter Property="cm:Message.Attach"
Value="ClickAction()"/>
<Setter Property="ef:KeyTip.Keys"
Value="{Binding KeyTip}"/>
<Setter Property="ToolTip">
<Setter.Value>
<ef:ScreenTip Title="{Binding DisplayName}"
HelpTopic="ScreenTip help ..."
Image="{Binding LargeIconPath}"
Text="Text for ScreenTip"/>
</Setter.Value>
</Setter>
</Style>
</ef:DropDownButton.ItemContainerStyle>
<ef:DropDownButton.ToolTip>
<ef:ScreenTip Title="{Binding DisplayName}"
HelpTopic="ScreenTip help ..."
Image="{Binding LargeIconPath}"
Text="Text for ScreenTip"/>
</ef:DropDownButton.ToolTip>
</ef:DropDownButton>
For some reason approach when Image is static resource with x:Shared = false doesn't work for me. Only last menu item shows icon. I've tried both StaticResource and DynamicResource. Here is my solution:
public class MenuItemIconHelper
{
#region ImageSource Icon
public static readonly DependencyProperty IconProperty = DependencyProperty.RegisterAttached("Icon", typeof(ImageSource), typeof(MenuItemIconHelper), new PropertyMetadata(default(ImageSource), IconPropertyChangedCallback));
private static void IconPropertyChangedCallback(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var i = (MenuItem)obj;
if (e.NewValue != null)
i.Icon = new Image() {Source = (ImageSource)e.NewValue};
else
i.Icon = null;
}
public static void SetIcon(DependencyObject element, ImageSource value)
{
element.SetValue(IconProperty, value);
}
public static ImageSource GetIcon(DependencyObject element)
{
return (ImageSource)element.GetValue(IconProperty);
}
#endregion
}
Sample:
<Style x:Key="CommandMenuItemStyle" TargetType="MenuItem">
<Setter Property="cb:MenuItemIconHelper.Icon" Value="car1.png" />
<Setter Property="Header" Value="{Binding Name}" />
I consider it to be more readable than using resource and you don't need to change MenuItem's HeaderTemplate. You can also implement some caching mechanism for ImageSource or Image.
1. Add Existing File... image file to resources (if you already have one, skip it).
2. In Solution Explorer select this image file.
3. Change Build Action to Resource.
And finally, you can add this image to XAML with simple call:
<Window.Resources>
<ContextMenu x:Key="contextMenu" >
<MenuItem Header="Restart" Name="menuItemRestart" Click="MenuItem_Click">
<MenuItem.Icon>
<Image Source="/Resources/restart.png"/>
</MenuItem.Icon>
</MenuItem>
<Separator/>
<MenuItem Header="Exit" Name="menuItemExit" Click="MenuItem_Click">
<MenuItem.Icon>
<Image Source="/Resources/window_close.png"/>
</MenuItem.Icon>
</MenuItem>
</ContextMenu>
</Window.Resources>
The Result: