I'm using a XamDataGrid (Infragistics-control) to display some hierarchical data. The objects that I can have up to 10 levels and I need to be able to give each level a specific background-color. I use the AssigningFieldLayoutToItem-event to get the "level" of the item and it would be best to assign the background/style here as well, I suppose.
I have tried specifying a DataRecordCellArea-style and even a CellValuePresenter-style but I can't get any of these to work with the FieldLayouts.
Another solution is to write a FieldLayout for each level, but this would create a lot of unnecessary XAML-code.
Any suggestions as to what I should do?
If you have a different FieldLayout for each level, you could use a single style targeting the DataRecordPresenter with a converter to set the background.
XAML:
<local:BackgroundConverter x:Key="BackgroundConverter"/>
<Style TargetType="{x:Type igDP:DataRecordPresenter}">
<Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Path=FieldLayout.Key, Converter={StaticResource BackgroundConverter}}"/>
</Style>
Converter:
public class BackgroundConverter:IValueConverter
{
public BackgroundConverter()
{
this.Brushes = new Dictionary<string, Brush>();
}
public Dictionary<string, Brush> Brushes {get;set;}
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is string)
{
string key = value.ToString();
if (this.Brushes.ContainsKey(key))
return this.Brushes[value.ToString()];
}
return Binding.DoNothing;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
The following will set the colors to use for fields with Key1 and Key2:
BackgroundConverter backgroundConverter = this.Resources["BackgroundConverter"] as BackgroundConverter;
backgroundConverter.Brushes.Add("Key1", Brushes.Green);
backgroundConverter.Brushes.Add("Key2", Brushes.Yellow);
If you are reusing the same FieldLayout for multiple fields, then you could use the InitializeRecord event and change the style to bind to the Tag of the DataRecord like this:
XAML:
<Style TargetType="{x:Type igDP:DataRecordPresenter}">
<Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Path=Record.Tag}"/>
</Style>
C#:
void XamDataGrid1_InitializeRecord(object sender, Infragistics.Windows.DataPresenter.Events.InitializeRecordEventArgs e)
{
if (!e.ReInitialize)
{
// Set the tag to the desired brush.
e.Record.Tag = Brushes.Blue;
}
}
Note that I didn't add the conditional logic for determining the brush to use and that still needs to be done for different levels to have different backgrounds.
Related
I have something like this:
public class Member {
public int Id { get; set; }
public string Name { get; set; }
public string Age { get; set; }
...
}
List<Member> members = new List<Member>{ new Member(Id = 1, Name="Chuck", Age="32"), new Member(Id = 2, Name="Eve", Age="10")};
Listbox1.ItemsSource = members;
How can I change the background of items in the ListBox, if the age is less than 18?
Setting the background of a ListBoxItem can be done by changing the item container style. Conditional setting of the color however requires a IValueConverter. You can write your own for checking Age. Please consider making Age a property of type int, otherwise you will have to parse it on each conversion from string.
public class AgeToColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return int.Parse((string)value) < 18 ? new SolidColorBrush(Colors.Red) : new SolidColorBrush(Colors.Blue);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new InvalidOperationException("This is a one-way conversion.");
}
}
XAML solution
In XAML you would create an instance of your converter in the resouces of the list box or any other resource dictionary. Then you would bind the ItemsSource to your members property and add a custom items container style. The style is based on the default style for the ListBoxItem. In it you bind the Background property to Age with your custom converter, which will convert the age string to a solid color brush.
<ListBox x:Name="Listbox1" ItemsSource="{Binding members}">
<ListBox.Resources>
<local:AgeToColorConverter x:Key="AgeToColorConverter"/>
</ListBox.Resources>
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource {x:Type ListBoxItem}}">
<Setter Property="Background" Value="{Binding Age, Converter={StaticResource AgeToColorConverter}}"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
Code-Behind solution
Suppose you defined your list box in XAML like this.
<ListBox x:Name="Listbox1"/>
Then the same as for the XAML solution applies to this code, except for we create the converter as a local variable and the items source is directly assigned instead of a binding.
var ageToColorConverter = new AgeToColorConverter();
var baseItemContainerStyle = (Style)FindResource(typeof(ListBoxItem));
var itemContainerStyle = new Style(typeof(ListBoxItem), baseItemContainerStyle);
var backgroundSetter = new Setter(BackgroundProperty, new Binding("Age") { Converter = ageToColorConverter });
itemContainerStyle.Setters.Add(backgroundSetter);
Listbox1.ItemContainerStyle = itemContainerStyle;
Listbox1.ItemsSource = members;
Is there a way to bind underline?? I'm trying to achieve the following:
I have VievModel with a bool property:
public bool HomeButtonUnderline { get; set; } = false;
I would then like to control this property in the following function:
public void Home() {
//CurrentPage = ApplicationPage.Home;
//HomeButtonForeground = new SolidColorBrush(Colors.White);
HomeButtonUnderline = true;
SettingsButtonUnderline = false;
}
I could then utilize this control in XAML:
<Button>
<TextBlock Command="{Binding HomeNavCommand}" Underline="{Binding HomeButtonUnderline}"/>
</Button>
The problem is that there isn't an 'Underline' property, instead it is handled by 'TextDecorations':
<Button>
<TextBlock TextDecorations="Underline">
</Button>
So is there a way to control underline using MVVM or even without it??
You may use a DataTrigger in a Style for the TextBlock:
<Button Command="{Binding HomeNavCommand}">
<TextBlock Text="Home">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Style.Triggers>
<DataTrigger Binding="{Binding HomeButtonUnderline}" Value="True">
<Setter Property="TextDecorations" Value="Underline"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</Button>
Use a Converter to convert your model types (in this case, a bool) to the UI types (in this case, a TextDecoration).
public class UnderlineConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return null;
return System.Convert.ToBoolean(value) ? TextDecorations.Underline : null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
And then use it in your binding (after creating a resource in your Window, UserControl App.xaml or whereever you feel is the right place; for this sample I'm just putting it in the button resources)
<Button Command="{Binding HomeNavCommand}">
<Button.Resources>
<local:UnderlineConverter x:Key="UnderlineConverter" />
</Button.Resources>
<TextBlock TextDecorations="{Binding HomeButtonUnderline, Converter={StaticResource UnderlineConverter}"/>
</Button>
Of course, another way to handle this is for your view model to be the right type for the view:
public TextDecorationCollection HomeButtonUnderline { get; set; }
HomeButtonUnderline is already GUI-orientated, so there's probably some code in your viewmodel that assigns a value from the model, so it might as well also convert from bool to TextDecorations.Underline.
This method keeps all the logic in the same file, unlike a converter, although a converter is more reusable. It also has the advantage of being easily unit-testable (unlike a data trigger).
I have a Resource (.resx) with a log of svg images in it. Furthermore I use an ImageResource class that can take the byte[] provided by the resource and convert it into an ImageSource Object.
While doing that, I have the possibility to Change the color of the Icon
ImageResource.CreateFromSvg(image, Brushes.Green);
I was searching for an easy way to get these Images into xaml, so I created another static class that creates an Image using the ImageResource class. In xaml I could use
<Image Source={x:Static img:ImageResources.MyGreenIcon}/>
to get the icon. The downside was, that I was not able to choose the color in xaml. So I tried and created a MarkupExtension for that. It takes a byte[] and a Brush as parameters, calls the CreateFromSvg-Method and returns the Image. In Xaml it looks like this
<Image Source={i:Img {x:Static img:SvgResources.TheIcon}, Green}/>
Where SvgResources is the .resx-file the Image is in.
Although this works well, I was not able to change the color at runtime. Because MarkupExtension is not a DependencyProperty I can not use a binding for the color. I tried to use a trigger
<Style TargetType="{x:Type Image}">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="Source" Value="{i:Img {x:Static img:SvgResources.TheIcon}, Blue}" />
</Trigger>
</Style.Triggers>
</Style>
This does not give any error, but just do nothing. So my questions are
How can I reassign the Source of the Image to get another color
Is there a way to use something like a binding to change the color from VM
Is there a way to shorten the {x:Static img:SvgResources.TheIcon to something like svgResource.TheIcon
Edit
I found out, that the Trigger does change the Source if I don't set the source in the control itself, but instead provide a default value in the trigger (IsMouseOver = false). Questions 2 + 3 still remain
Answer to question 2.
You can extend your MarkupExtension to support Binding with MultiValueConverter.
Create simple MultiValueConverter, which will simply call your ImageResource.CreateFromSvg(...);. Values passed to this converter will be image and Brush (static image or brush resolved from Bindings)
In ProvideValue(...) detect is passed value Brush or Binding. If it's Brush create mock Binding for it with this Brush as Source.
If value is Binding - we will use it. Do same for image
Create Multibinding, assign just created MultiValueConverter and add image and brush bindings.
return provided value.
Complete example of Img MarkupExtension:
public class Img : MarkupExtension
{
private readonly object _image;
private readonly object _brush;
public Img(object image, object brush)
{
_image = image;
_brush = brush;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
var imageBinding = _image is Binding iBinding ? iBinding : new Binding { Source = _image};
var brushBinding = _brush is Binding bBinding ? bBinding : new Binding { Source = _brush };
var binding = new MultiBinding
{
Converter = new ImgValueConverter()
};
binding.Bindings.Add(imageBinding);
binding.Bindings.Add(brushBinding);
return binding.ProvideValue(serviceProvider);
}
private class ImgValueConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
var image = values[0];
var brush = values[1];
return ImageResource.CreateFromSvg(image, brush);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
Usage example:
<Image Source="{i:Img {x:Static i:SvgResources.TheIcon}, {x:Static Brushes.Yellow}}"/>
<Image Source="{i:Img {x:Static i:SvgResources.TheIcon}, {Binding Brush}}"/>
I have a WPF Solution with 2 projects, the first one (ResourcesLibrary) contains common styles and common resources. The other is the WPF application.
I created a style for DataGridRows in the ResourcesLibrary generic.xaml file:
<Style x:Key="DGRowStyle" TargetType="{x:Type DataGridRow}">
<Setter Property="ValidationErrorTemplate">
<Setter.Value>
<ControlTemplate>
<Image Source="/Resources/stop.png"
ToolTip = "{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGridRow}},
Path=(Validation.Errors),
Converter={StaticResource errorConverter]}}"/>
</ControlTemplate>
</Setter.Value>
</Setter>
I added the .cs converter files to the ResourcesLibrary project:
namespace ResourceLibrary
{
public class ErrorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var errors = value as ReadOnlyObservableCollection<ValidationError>;
if (errors == null)
return "";
return errors.Count > 0 ? errors[0].ErrorContent : "";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
And added the reference and the static resource:
xmlns:my="clr-namespace:ResourceLibrary"
<!-- CONVERTERS -->
<my:ErrorConverter x:Key="errorConverter" />
But at runtime when, in the main project, I use the DataGridRow style defined in the ResourcesLibrary I get this error:
{"Cannot find resource named 'errorConverter]'. Resource names are case sensitive."}
Do I need to have another project inside my solution for the converters I will use?
Thanks to #Clemens I removed the extra char ']' in the expression "={StaticResource errorConverter]}" and it all works fine.
I'm trying to create a custom control - a button - which will have multiple styles applied to it depending on the value of a property within the data context.
What I was thinking is using something similar to:
<Button Style="{Binding Path=ButtonStyleProperty, Converter={StaticResource styleConverter}}" Text="{Binding Path=TextProp}" />
And in code... Implement an IValueConverter which does something similar to the code below in the ConvertTo method:
switch(value as ValueEnums)
{
case ValueEnums.Enum1:
FindResource("Enum1ButtonStyle") as Style;
break;
... and so on.
}
However I'm not entirely sure about how to pull out the style object and even if this is possible at all...
What I am doing in the mean time is handling the DataContextChanged event, then attaching a handler to the PropertyChanged event of the object being bound to the button - then running the switch statement in there.
Its not quite perfect but until I can find a better solution it seems like that is what I'll have to use.
If you want to replace the whole style (rather than just elements of it) then you'll probably be storing those styles in resources. You should be able to do something along the lines of:
<Button>
<Button.Style>
<MultiBinding Converter="{StaticResource StyleConverter}">
<MultiBinding.Bindings>
<Binding RelativeSource="{RelativeSource Self}"/>
<Binding Path="MyStyleString"/>
</MultiBinding.Bindings>
</MultiBinding>
</Button.Style>
</Button>
By using a MultiBinding and using Self as the first binding we can then lookup resources in our converter. The converter needs to implement IMultiValueConverter (rather than IValueConverter) and can look something like this:
class StyleConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
FrameworkElement targetElement = values[0] as FrameworkElement;
string styleName = values[1] as string;
if (styleName == null)
return null;
Style newStyle = (Style)targetElement.TryFindResource(styleName);
if (newStyle == null)
newStyle = (Style)targetElement.TryFindResource("MyDefaultStyleName");
return newStyle;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
It's not something I do very often, but that should work from memory :)
It seems that you need to use DataTrigger class. It allows you to apply different styles to your button based on it's content.
For example following style will change button's background property to red based on value of data context object's property
<Style x:Key="ButtonStyle" TargetType="{x:Type Button}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path="Some property"}"
Value="some property value">
<Setter Property="Background" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
For those of us who can't use multi value converter (I'm looking at you SL4 and WP7:), thanks to Steven's answer I found a way using an ordinary value converter.
The only assumption is the style value is contained within the property of the style being set.
So if you're using the MVVM pattern then the style value (such as TextSmall, TextMedium, TextLarge) is assumed to be part of the view model, and all you have to do is pass the converter parameter defining the name of style.
For example, say your view model has property:
public string ProjectNameStyle
{
get { return string.Format("ProjectNameStyle{0}", _displaySize.ToString()); }
}
Application style:
<Application.Resources>
<Style x:Key="ProjectNameStyleSmall" TargetType="TextBlock">
<Setter Property="FontSize" Value="40" />
</Style>
<Style x:Key="ProjectNameStyleMedium" TargetType="TextBlock">
<Setter Property="FontSize" Value="64" />
</Style>
<Style x:Key="ProjectNameStyleLarge" TargetType="TextBlock">
<Setter Property="FontSize" Value="90" />
</Style>
XAML view:
<TextBlock
Text="{Binding Name}"
Style="{Binding ., Mode=OneWay, Converter={cv:StyleConverter}, ConverterParameter=ProjectNameStyle}">
With your StyleConverter class implementing IValueConverter:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (targetType != typeof(Style))
{
throw new InvalidOperationException("The target must be a Style");
}
var styleProperty = parameter as string;
if (value == null || styleProperty == null)
{
return null;
}
string styleValue = value.GetType()
.GetProperty(styleProperty)
.GetValue(value, null)
.ToString();
if (styleValue == null)
{
return null;
}
Style newStyle = (Style)Application.Current.TryFindResource(styleValue);
return newStyle;
}
Note that this is WPF code, as the converter is derived from a MarkupExtension as well as IValueConverter, but it will work in SL4 and WP7 if you use static resource and add a bit more leg work as the TryFindResource method doesn't exist.
Hope that helps someone, and thanks again Steven!
ViewModel
private Style _dynamicStyle = (Style)Application.Current.FindResource("Style1");
public Style DynamicStyle
{
get { return _dynamicStyle; }
set
{
_dynamicStyle = value;
OnPropertyChanged("DynamicStyle");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
Implement a property in your ViewModel and then dynamically change style where ever you want like below.
DynamicStyle=(Style)Application.Current.FindResource("Style2");// you can place this code where the action get fired
View
Then set DataContext value and then implement the following code in your view
<Button Style="{Binding DynamicStyle,Mode=TwoWay}"/>