How to style auto-generated elements in xaml - c#

I'm using this extension this toolkit, it automatically adds a TextBox to the top of each DataGrid column for filtering from the following code.
<DataGrid ColumnHeaderStyle="{StaticResource {ComponentResourceKey
TypeInTargetAssembly={x:Type filter:DataGridHeaderFilterControl},
ResourceId=DataGridHeaderFilterControlStyle}}" >
However, the added column header and the textboxes have a different style from what I want.
So I can do this to style the column header, but it won't change the textboxes.
<Style x:Key="FilterHeader"
BasedOn="{StaticResource {ComponentResourceKey TypeInTargetAssembly={x:Type filter:DataGridHeaderFilterControl},
ResourceId=DataGridHeaderFilterControlStyle}}"
TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="Foreground" Value="Blue" />
</Style>
...
<DataGrid ColumnHeaderStyle="{DynamicResource FilterHeader}">
I tried putting this inWindow.Resources to see if it had an effect on the textboxes. It changed my other textboxes it doesn't have any effect on the textboxes created by the extension.
<Style TargetType="TextBox">
<Setter Property="Foreground" Value="Blue" />
</Style>
But no dice. The only thing I've found that works is this:
public void DataGrid_OnLoad(object sender, RoutedEventArgs e)
{
IEnumerable<System.Windows.Controls.TextBox> collection =
FindVisualChildren<System.Windows.Controls.TextBox>(TitleBar);
foreach (System.Windows.Controls.TextBox tb in collection)
{
tb.Foreground = Brushes.Blue;
}
}
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
But that seems like a garbage way of doing it. How can I do this purely in xaml or at least more cleanly in C#?

From looking through the source code, i noticed that the TextBox isn't really a textbox but a subclass of Textbox. DelayTextBox
So you could just modify your style to target that instead.
<Style TargetType="DelayTextBox">
<Setter Property="Foreground" Value="Blue" />
</Style>
I haven't tried it but it should work.
Update
Finally found the issue. The styles should be defined within a style of their parent.
<Style TargetType="{x:Type filter:DataGridColumnFilter}">
<Style.Resources>
<Style TargetType="{x:Type support:DelayTextBox}">
<Setter Property="Foreground" Value="Blue" />
<Setter Property="FontWeight" Value="Bold"/>
</Style>
<Style TargetType="{x:Type ComboBox}">
<Setter Property="Foreground" Value="Blue" />
<Setter Property="FontWeight" Value="Bold"/>
</Style>
</Style.Resources>
</Style>
I've added the comboxbox since i assume you'd want that too. you can take out the setter for bold as needed .. was using it to test.

Related

EditingElementStyle in a DataGridTextColumn

I need to be able to distinguish from which column in a DataGrid, a TextBox has been edited:
<DataGridTextColumn Header="No" Binding="{Binding NumberOfItems}">
<DataGridTextColumn.EditingElementStyle>
<Style TargetType="{x:Type TextBox}" x:Name="NumOfItems">
<Setter Property="MaxLength" Value="2"/>
</Style>
</DataGridTextColumn.EditingElementStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="Role" Binding="{Binding Role}" Width="0.75*">
<DataGridTextColumn.EditingElementStyle>
<Style TargetType="{x:Type TextBox}" x:Name="Role">
<Setter Property="MaxLength" Value="30"/>
</Style>
</DataGridTextColumn.EditingElementStyle>
</DataGridTextColumn>
so that I can update a database with the correct information. I have tried to use x:Name but, with the code below, the name is always empty
private void dgItems_CellEditEnding(object sender,
DataGridCellEditEndingEventArgs e)
{
if(e.EditingElement is TextBox)
{
TextBox t = e.EditingElement as TextBox;
..........
if (t.Name == "Role")
//do this
else if (t.NumOfItems)
//do this
}
Thanks for any help
You could set the Tag property in the Style:
<Style TargetType="{x:Type TextBox}">
<Setter Property="MaxLength" Value="30"/>
<Setter Property="Tag" Value="Role"/>
</Style>
if (t.Tag?.ToString() == "Role")

C# WPF Treeview ItemContainerStyle makes mouseclick event sender lose TreeviewItem reference

I have this code that works,
private void TreeSetup_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
if (sender is TreeViewItem)
{
((TreeViewItem)sender).IsSelected = true;
}
e.Handled = true;
}
private void TreeSetup_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
ContextMenu PopupMenu = this.FindResource("cmButton") as ContextMenu;
if (TreeSetup.SelectedItem != null)
{
PopupMenu.PlacementTarget = sender as TreeViewItem;
PopupMenu.IsOpen = true;
}
}
But once I add this ItemContainerStyle,
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="IsSelected" Value="{Binding Path=IsSelected, Mode=TwoWay}" />
<Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}"/>
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="FontWeight" Value="Bold" />
</Trigger>
</Style.Triggers>
</Style>
</TreeView.ItemContainerStyle>
My sender on the mouse down event becomes a TreeView instead of TreeViewItem.
Does anyone know the cause and fix to this?
I binded the mousedown event under the ItemContainerStyle:
<TreeView.ItemContainerStyle>
<Style TargetType="TreeViewItem">
<EventSetter Event="MouseRightButtonDown" Handler="TreeSetup_MouseRightButtonDown"/>
<Setter Property="IsSelected" Value="{Binding Path=IsSelected, Mode=TwoWay}" />
<Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}"/>
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="FontWeight" Value="Bold" />
</Trigger>
</Style.Triggers>
</Style>
</TreeView.ItemContainerStyle>

XAML How apply styles according the value of paramter

The goal is to check the state of parameters, the state of each parameter can take the enum value (lock, unlock, or valueIncorrect). The display
will be different according to the state of the parameter(e.g, lock rectangle will be red, unlock the text will be bold and vallueIncorrect will be gray).
In main class we have different parameters VarA, VarB and VarC for example. The state of each parameter can be different.
enum State{lock, unlock, valueIncorrect};
State VarA = lock
State VarB = unlock
State VarC = lock
before I was this style and a rectangle based on this style and When I pressed a button , the style will change, but the reaction will be the same on all parameter
<Style x:Key="DisplayLockGroup" TargetType="GroupBox">
<Setter Property="BorderThickness" Value="2"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Source={x:Static local:LockMgt.Instance}, Path=isLocked}" Value="true">
<Setter Property="BorderBrush" Value="Red" />
</DataTrigger>
<DataTrigger Binding="{Binding Source={x:Static local:LockMgt.Instance}, Path=isLocked}" Value="false">
<Setter Property="BorderBrush" Value="Green" />
</DataTrigger>
</Style.Triggers>
</Style>
<Rectangle x:Name="r_LockEcuTypes" Grid.Row="5" Grid.RowSpan="3" Grid.Column ="1" Grid.ColumnSpan="7" Style="{DynamicResource DisplayLockRectangleGroup}" />
Now i would like to change this behavior, I have different parameter and I would like to individually check the state of this parameter and apply one style according to the value, but i don't know How I can do it.
E.g for one parameter:
State VarA=lock => i would like to apply the style1
State VarB=unlock => i would like to apply the style2
State VarC=lock => i would like to apply the style1 but if the value change from lock to unlock, I would like to apply the style2
I don't know how create the XAML to display correctly what is expected.
As commented, depending on your actual needs, you have several options.
Converter from State to some property value
Change the properties via Style.Triggers (similar to your current approach)
Wrap your control and exchange inner styles via ControlTemplate.Triggers on the wrapper control
The following example is presenting three rectangles (rect1, rect2 and rect3 representing the approach with the same number) and a button that is responsible for changing the State of the ViewModel object in order to show how each rectangle reacts.
The XAML
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication2"
Title="MainWindow" Height="350" Width="525"
Loaded="Window_Loaded">
<Window.Resources>
<!-- Used for 1. -->
<local:StateToBorderBrushConverter x:Key="stateConverter"/>
<!-- Used for 2. -->
<Style x:Key="DisplayLockGroup" TargetType="Rectangle">
<Setter Property="StrokeThickness" Value="2"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Data1State}" Value="{x:Static local:State.locked}">
<Setter Property="Stroke" Value="Red" />
</DataTrigger>
<DataTrigger Binding="{Binding Data1State}" Value="{x:Static local:State.unlock}">
<Setter Property="Stroke" Value="Green" />
</DataTrigger>
</Style.Triggers>
</Style>
<!-- Used for 3. -->
<Style x:Key="DefaultRectangleStyle" TargetType="Rectangle">
<Setter Property="StrokeThickness" Value="2"/>
</Style>
<Style x:Key="LockedRectangleStyle" TargetType="Rectangle">
<Setter Property="StrokeThickness" Value="2"/>
<Setter Property="Stroke" Value="Red" />
</Style>
<Style x:Key="UnlockedRectangleStyle" TargetType="Rectangle">
<Setter Property="StrokeThickness" Value="2"/>
<Setter Property="Stroke" Value="Green" />
</Style>
</Window.Resources>
<Grid x:Name="grid1">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Rectangle x:Name="rect1" Grid.Row="0" Margin="5" StrokeThickness="2" Stroke="{Binding Data1State,Converter={StaticResource stateConverter}}" />
<Rectangle x:Name="rect2" Grid.Row="1" Margin="5" Style="{StaticResource DisplayLockGroup}" />
<ContentControl Margin="5" Grid.Row="2">
<ContentControl.Template>
<ControlTemplate TargetType="ContentControl">
<Rectangle x:Name="rect3" Style="{StaticResource DefaultRectangleStyle}" />
<ControlTemplate.Triggers>
<DataTrigger Binding="{Binding Data1State}" Value="{x:Static local:State.locked}">
<Setter TargetName="rect3" Property="Style" Value="{StaticResource LockedRectangleStyle}"/>
</DataTrigger>
<DataTrigger Binding="{Binding Data1State}" Value="{x:Static local:State.unlock}">
<Setter TargetName="rect3" Property="Style" Value="{StaticResource UnlockedRectangleStyle}"/>
</DataTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</ContentControl.Template>
</ContentControl>
<Button x:Name="ChangeStateButton" Grid.Row="3" Margin="5" VerticalAlignment="Center" Content="Change State" Click="ChangeStateButton_Click"/>
</Grid>
</Window>
The Code
namespace WpfApplication2
{
public enum State
{
locked,
unlock,
valueIncorrect
}
public class BaseViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged([CallerMemberName] string prop = null)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(prop));
}
}
}
public class MyData : BaseViewModel
{
private State _Data1State;
public State Data1State
{
get { return _Data1State; }
set
{
if (_Data1State != value)
{
_Data1State = value;
NotifyPropertyChanged();
}
}
}
}
public class StateToBorderBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is State)
{
var s = (State)value;
switch (s)
{
case State.locked:
return new SolidColorBrush(Colors.Red);
case State.unlock:
return new SolidColorBrush(Colors.Green);
case State.valueIncorrect:
return new SolidColorBrush(Colors.White);
default:
break;
}
}
return new SolidColorBrush(Colors.Transparent);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private MyData ContextData;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
ContextData = new MyData { Data1State = State.locked };
grid1.DataContext = ContextData;
}
private void ChangeStateButton_Click(object sender, RoutedEventArgs e)
{
switch (ContextData.Data1State)
{
case State.locked:
ContextData.Data1State = State.unlock;
break;
case State.unlock:
ContextData.Data1State = State.valueIncorrect;
break;
case State.valueIncorrect:
ContextData.Data1State = State.locked;
break;
default:
ContextData.Data1State = State.locked;
break;
}
}
}
}
Pros and cons:
The converter approach is useful, if the same property type is targeted in many different control types. The converter is returning a Brush and it doesn't care whether that brush will be used in a Rectangle.Stroke, a Border.BorderBrush or some other context.
The style trigger approach is less flexible regarding the targeted control type, but it is easier to maintain changes of more than a single property based on the status.
The control template trigger approach is useful in some advanced scenarios. It allows separate definition of the styles for each state. However, I'd only recommend it if you actually derive your own custom control with additional functionality, not as an ad-hoc control template just for switching styles.
You can apply an enum to color converter in the XAML binding
Background="{Binding Source=StateValue,
Converter={StaticResource stateValueColorConverter}}"
You'll easily find the detailed documentation: this is to give you the main idea of the usage.
Thanks to grek40, it is exactly what I want. I have try the option 3 and 2 and it works fine, I have use the case 2, it is most easily to implement.
I have use the same behavior for add an image on lock and unlock state.
In the Xaml.cs file, How I can access to parameter rect3 on your proposal, when I try it I have compilation error "the name "rect3" does not exist in the current view, I have written
XAML.CS :
rect3.Visibility = Visibility.Collapsed;
XAML :
<ContentControl Grid.RowSpan="3" Grid.ColumnSpan="3" KeyboardNavigation.IsTabStop="False">
<ContentControl.Template>
<ControlTemplate TargetType="ContentControl">
<Rectangle x:Name="rect3" Style="{StaticResource DefaultRectangleStyle}" />
<ControlTemplate.Triggers>
<DataTrigger Binding="{Binding Data1State}" Value="{x:Static local:State.locked}">
<Setter TargetName="rect3" Property="Style" Value="{StaticResource LockedRectangleStyle}"/>
</DataTrigger>
<DataTrigger Binding="{Binding Data1State}" Value="{x:Static local:State.unlock}">
<Setter TargetName="rect3" Property="Style" Value="{StaticResource UnlockedRectangleStyle}"/>
</DataTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</ContentControl.Template>
</ContentControl>

How to change background color for some cell in WPF DataGrid?

I have a datagrid binded to an object collection.
One property of the objects is a string that store a color value.
On this "COLORBACKGROUND" cell click, a colorpicker opens to change it.
What I need is to change the background color of the cell by the value displayed in datagrid rows (#RGB).
<DataGrid SelectionUnit="Cell" SelectedCellsChanged="DgDataTable_OnSelectedCellsChanged" x:Name="DgDataTable" Grid.Row="0" Grid.ColumnSpan="2" Margin="10,20,10,0" AutoGenerateColumns="true" HeadersVisibility="All" RowHeaderWidth="20" Style="{StaticResource AzureDataGrid}" GridLinesVisibility="Horizontal" LoadingRow="dgDataTable_LoadingRow" ColumnHeaderHeight="10" AlternatingRowBackground="{DynamicResource {x:Static SystemColors.GradientActiveCaptionBrushKey}}" AutoGeneratingColumn="DgDataTable_AutoGeneratingColumn">
<DataGrid.RowHeaderStyle>
<Style TargetType="DataGridRowHeader">
<Setter Property="FontSize" Value="10"/>
<Setter Property="Background" Value="LightCyan"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
</Style>
</DataGrid.RowHeaderStyle>
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="TextBlock.TextAlignment" Value="Center"/>
<!-- <Style.Triggers>
<Trigger Property="Text" Value="John">
<Setter Property="Background" Value="LightGreen"/>
</Trigger>
</Style.Triggers> -->
</Style>
</DataGrid.CellStyle>
</DataGrid>
I tried something with AutoGenerating column :
private void DgDataTable_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyName == "SrcAlert")
{
DataGridComboBoxColumn cb = new DataGridComboBoxColumn();
e.Column = cb;
cb.ItemsSource = new List<string> {"1", "2"};
cb.SelectedValueBinding = new Binding("SrcAlert");
e.Column.Header = "SrcAlert";
}
if (e.PropertyName.Equals("ColorBackground"))
{
DataGridTextColumn tc = new DataGridTextColumn();
e.Column = tc;
tc.Foreground = (Color)ColorConverter.ConvertFromString(DgDataTable.CurrentCell.Item.ColorBackground);
}
}
this Item.ColorBackground doesn't compile... I put it for my explanation, thats what I need.
I tried another solution I found :
if (e.PropertyName.Equals("ColorBackground"))
{
string s = DgDataTable.CurrentCell.Item.ToString();
e.Column.CellStyle.Setters.Add(new Setter(DataGridCell.BackgroundProperty, (Color)ColorConverter.ConvertFromString(s)));
}
but that was a fail.
Thank you for your help !
Edit : A screenshot of ASh solution that works perfectly for me:
EDIT : I adapted your solution for multiple columns with color Picker :
I add style setters to display only colors in the cells :
<Style TargetType="DataGridCell" x:Key="ColorPickerCellBG"
BasedOn="{StaticResource CommonCell}">
<Setter Property="Background" Value="{Binding Path=BG}"/>
<Setter Property="Foreground" Value="Transparent"/>
<Setter Property="Width" Value="30"></Setter>
</Style>
<Style TargetType="DataGridCell" x:Key="ColorPickerCellAL"
BasedOn="{StaticResource CommonCell}">
<Setter Property="Background" Value="{Binding Path=AL}"/>
<Setter Property="Foreground" Value="Transparent"/>
<Setter Property="Width" Value="30"></Setter>
</Style>
<Style...
When the cell is clicked, the rgb color value is visible, the style must be "ClickedCell"...
How can I Improve that ?
it is possible to apply special style to a single auto-generated column.
declare two cell styles in resources
<Window.Resources>
<Style TargetType="DataGridCell" x:Key="CommonCell"
BasedOn="{StaticResource {x:Type DataGridCell}}">
<Setter Property="TextBlock.TextAlignment" Value="Center"/>
</Style>
<Style TargetType="DataGridCell" x:Key="ColorPickerCell"
BasedOn="{StaticResource CommonCell}">
<Setter Property="Background" Value="{Binding Path=ColorBackground}"/>
</Style>
</Window.Resources>
ColorPickerCell inherits CommonCell style.
<DataGrid SelectionUnit="Cell"
x:Name="DgDataTable"
AutoGenerateColumns="true" HeadersVisibility="All" RowHeaderWidth="20"
GridLinesVisibility="Horizontal"
ColumnHeaderHeight="10"
AlternatingRowBackground="{DynamicResource {x:Static SystemColors.GradientActiveCaptionBrushKey}}"
CellStyle="{StaticResource CommonCell}"
AutoGeneratingColumn="DgDataTable_AutoGeneratingColumn">
<DataGrid.RowHeaderStyle>
<Style TargetType="DataGridRowHeader">
<Setter Property="FontSize" Value="10"/>
<Setter Property="Background" Value="LightCyan"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
</Style>
</DataGrid.RowHeaderStyle>
</DataGrid>
change CellStyle for a generated column:
private void DgDataTable_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyName == "ColorBackground")
{
e.Column.CellStyle = (sender as DataGrid).FindResource("ColorPickerCell") as Style;
}
}
Apply a Converter, this Converter is used for two diff. purpose hence returns two diff types. Beauty of this approach is : You can change the property in XAML itself. No change needed in code now, and hence it is MVVM friendly.
For example, in DataTrigger change Value=BkgProp to Value=Name and see.
Sample XAML :
<Window ...>
<Window.Resources>
<local:PropBasedStringToColorConverter x:Key="StringToColorCnvKey"/>
</Window.Resources>
<Grid>
<DataGrid x:Name="Dgrd">
<DataGrid.Resources>
<Style TargetType="DataGridCell">
<Style.Triggers>
<DataTrigger Binding="{Binding .Column, RelativeSource={RelativeSource Self}, Converter={StaticResource StringToColorCnvKey}}" Value="BkgProp">
<Setter Property="Background" Value="{Binding BkgProp, Converter={StaticResource StringToColorCnvKey}}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.Resources>
</DataGrid>
</Grid>
</Window>
Sample Data :
Dgrd.ItemsSource = new[] { new { BkgProp = "#abcdef", Name = "Anjum" }, new { BkgProp = "#edf2ed", Name = "Anjum" }, new { BkgProp = "#ff0000", Name = "Anjum" } }.ToList();
Converter Code :
public class PropBasedStringToColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
object result = null;
if (value == null) return "N/A";
if (value.GetType() == typeof(DataGridTextColumn))
{
string path = ((Binding)((DataGridTextColumn)value).Binding).Path.Path;
return path;
}
else if (value.GetType() == typeof(string))
{
result = new SolidColorBrush((Color)ColorConverter.ConvertFromString(value.ToString()));
}
return result;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}

Design time check of markup extension arguments in WPF designer

I've written a Markup extension for WPF that allows me to do
<!-- Generic Styles -->
<Style x:Key="bold" TargetType="Label">
<Setter Property="FontWeight" Value="ExtraBold" />
</Style>
<Style x:Key="italic" TargetType="Label">
<Setter Property="FontStyle" Value="Italic" />
</Style>
<Style x:Key="gridHeader" TargetType="Label"
BasedOn="{WPF:CombiStyle bold italic }" >
It is a very usefull extension and it works great at runtime. However
at design time I can't see the styles applied or that if
I mistype bold and italic they might not be found
as StaticResources.
Any hacks I can do to get this working?
The source code for the extension is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Markup;
namespace MarkupExtensions
{
[MarkupExtensionReturnType(typeof(Style))]
public class CombiStyleExtension : MarkupExtension
{
private string[] MergeStyleProviders { get; set; }
public CombiStyleExtension(string s0)
{
MergeStyleProviders = s0.Split(new[]{' '});
}
public override object ProvideValue(IServiceProvider
serviceProvider)
{
return MergeStyleProviders
.Select(x => StringToStyle(serviceProvider, x))
.Aggregate(new Style(), RecursivelyMergeStyles);
}
private static Style StringToStyle(IServiceProvider serviceProvider, string x)
{
var style = new StaticResourceExtension() { ResourceKey = x }.ProvideValue(serviceProvider) as Style;
if (style==null)
{
throw new ArgumentException("Argument could not be converted to a style");
}
return style;
}
private static Style RecursivelyMergeStyles(Style accumulator,
Style next)
{
if (next.BasedOn != null)
{
RecursivelyMergeStyles(accumulator, next.BasedOn);
}
MergeStyle(accumulator, next);
return accumulator;
}
private static void MergeStyle(Style targetStyle, Style sourceStyle)
{
targetStyle.TargetType = sourceStyle.TargetType;
// Merge the Setters...
foreach (var setter in sourceStyle.Setters)
targetStyle.Setters.Add(setter);
// Merge the Triggers...
foreach (var trigger in sourceStyle.Triggers)
targetStyle.Triggers.Add(trigger);
}
}
}
Update: added screenshots for VS2012 (works fine) and Blend for VS2012 (works partially: base styles on BasedOn-styles are not picked up correctly for some reason).
Also checked it in VS2013 Preview and Blend for VS2013 Preview - there it works partially and exactly the same as in Blend for VS2012. Hope they fix this in release.
The thing is that Visual Studio designer very likes when object that you try to describe in XAML has public default constructor that it use to instanciate design-time instance of that object.
I've updated a bit your CombiStyleExtension.cs class to take this into account and Visual Studio 2010 designer like it now. However Blend 4 designer still don't, sorry.
Take a look:
using System;
using System.Linq;
using System.Windows;
using System.Windows.Markup;
namespace WpfApplication7
{
[MarkupExtensionReturnType(typeof(Style))]
public class CombiStyleExtension : MarkupExtension
{
/// <summary>
/// Set space-separated style names i.e. "size16 grey verdana".
/// </summary>
public string Names { private get; set; }
public override object ProvideValue(IServiceProvider serviceProvider)
{
return Names.Split(new[] { ' ' })
.Select(x => Application.Current.TryFindResource(x)
as Style)
.Aggregate(new Style(), RecursivelyMergeStyles);
}
private static Style RecursivelyMergeStyles(Style accumulator,
Style next)
{
if(accumulator == null || next == null)
return accumulator;
if(next.BasedOn != null)
RecursivelyMergeStyles(accumulator, next.BasedOn);
MergeStyle(accumulator, next);
return accumulator;
}
private static void MergeStyle(Style targetStyle, Style sourceStyle)
{
if(targetStyle == null || sourceStyle == null)
{
return;
}
targetStyle.TargetType = sourceStyle.TargetType;
// Merge the Setters...
foreach(var setter in sourceStyle.Setters)
targetStyle.Setters.Add(setter);
// Merge the Triggers...
foreach(var trigger in sourceStyle.Triggers)
targetStyle.Triggers.Add(trigger);
}
}
}
Usage of this markup extension changed also just a bit. How it was:
BasedOn="{WPF:CombiStyle bold italic }"
and how it now:
BasedOn="{WPF:CombiStyle Names='bold italic'}"
And just to save some time for you here is a bit of xaml to copy-paste-run-and-watch:
MainWindow.xaml:
<Window x:Class="WpfApplication7.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:WPF="clr-namespace:WpfApplication7"
Title="MainWindow" Height="350" Width="569">
<Window.Resources>
<!-- Did not managed to make the type-level style work -->
<!-- from app.xaml, so put it here. Just in case. -->
<Style TargetType="{x:Type Label}"
BasedOn="{WPF:CombiStyle Names='size16 grey verdana'}" />
</Window.Resources>
<StackPanel>
<Label Content="Type-level: size16 + grey + verdana" />
<Label Content="'h1': size24 + royalBlue" Style="{DynamicResource h1}" />
<Label Content="'warning': size24 + yellow + bold + shadow"
Style="{DynamicResource warning}" />
<Label Content="Inline: size12 + italic"
Style="{WPF:CombiStyle Names='size12 italic'}" />
<Label Content="Inline: size16 + bold + italic + red"
Style="{WPF:CombiStyle Names='size16 bold italic red'}" />
<Label Content="Inline: size24 + green"
Style="{WPF:CombiStyle Names='size24 green'}" />
</StackPanel>
</Window>
App.xaml:
<Application x:Class="WpfApplication7.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:WPF="clr-namespace:WpfApplication7"
StartupUri="MainWindow.xaml">
<Application.Resources>
<!-- Sizes -->
<Style x:Key="size12" TargetType="Label">
<Setter Property="FontSize" Value="12" />
</Style>
<Style x:Key="size16" TargetType="Label">
<Setter Property="FontSize" Value="16" />
</Style>
<Style x:Key="size24" TargetType="Label">
<Setter Property="FontSize" Value="24" />
</Style>
<!-- Bold/Italic -->
<Style x:Key="bold" TargetType="Label">
<Setter Property="FontWeight" Value="ExtraBold" />
</Style>
<Style x:Key="italic" TargetType="Label">
<Setter Property="FontStyle" Value="Italic" />
</Style>
<!-- Colors -->
<Style x:Key="grey" TargetType="Label">
<Setter Property="Foreground" Value="#333333" />
</Style>
<Style x:Key="royalBlue" TargetType="Label">
<Setter Property="Foreground" Value="RoyalBlue" />
</Style>
<Style x:Key="green" TargetType="Label">
<Setter Property="Foreground" Value="Green" />
</Style>
<Style x:Key="yellow" TargetType="Label">
<Setter Property="Foreground" Value="Yellow" />
</Style>
<Style x:Key="red" TargetType="Label">
<Setter Property="Foreground" Value="#D00000" />
</Style>
<!-- Fonts -->
<Style x:Key="verdana" TargetType="Label">
<Setter Property="FontFamily" Value="Verdana" />
</Style>
<!-- Effects -->
<Style x:Key="shadow" TargetType="Label">
<Setter Property="Effect">
<Setter.Value>
<DropShadowEffect ShadowDepth="0" />
</Setter.Value>
</Setter>
</Style>
<!-- Predefined Combinations -->
<Style x:Key="h1" TargetType="{x:Type Label}"
BasedOn="{WPF:CombiStyle Names='size24 royalBlue'}" />
<Style x:Key="warning" TargetType="{x:Type Label}"
BasedOn="{WPF:CombiStyle Names='size24 yellow bold shadow'}">
<Setter Property="BorderThickness" Value="1" />
<Setter Property="BorderBrush" Value="Yellow" />
</Style>
</Application.Resources>
</Application>
Enjoy ;)
No Unfortunately, My understanding of the problem is this,
Design time resolution seems to work in WPF because of dependency properties. Since MarkupExtension is not derived from dependency object your extension is never evaluated at design time. As to weather this was an oversight or intentional is debatable.
There may be another way to solve this though which would be slightly different. Create a new attached property called MergeStyles. In that property you could specify the style names you wish to merge and apply. When the value is changed simply update the style of the attachee using your code above. You could use the position each style to be merged comes in to determine hierarchy.
It's not exactly what you want but it may get you half way there. The upshot to this is that you can bind to it though.

Categories

Resources