I have a reusable user control with a dependency property which sets the color of a rectangle. The property uses Brush as type.
The data binding works fine, however I would like to add a fallback and null value when the binding has errors or its value is not specified.
Here is my XAML:
<Rectangle Fill="{Binding Path=UnderLineColor, ElementName=Header,
FallbackValue=LightGrey, TargetNullValue=LightGrey}"
Height="2"
Margin="0,2"
Grid.Row="1"
Grid.ColumnSpan="2" />
And the code of the UnderLineColor DP:
public Brush UnderLineColor
{
get { return (Brush)GetValue(UnderLineColorProperty); }
set { SetValue(UnderLineColorProperty, value); }
}
public static readonly DependencyProperty UnderLineColorProperty =
DependencyProperty.Register("UnderLineColor", typeof(Brush), typeof(SectionHeader), null);
The issue is that SL doesn't seem to accept the fallback and nullvalue I specify.
What value should I write into these properties to make it work? Or should I use a ValueConverter instead of this approach?
Edit:
Top tip for today: Grey != Gray. Issue is fixed now. :)
Related
I need help with drawing in my combobox. I want to make a combobox of colors for picking. I found some stuff on the internet but none of them is working. So far I have this :
private void MyComb_DrawItem(object sender, DrawItemEventArgs e)
{
Graphics g = e.Graphics;
System.Drawing.Rectangle rect = e.Bounds;
ColorConverter converter = new ColorConverter();
if (e.Index >= 0)
{
string n = ((ComboBox)sender).Items[e.Index].ToString();
System.Drawing.Color c = (System.Drawing.Color)converter.ConvertFromString(n);
SolidBrush b = new SolidBrush(c);
g.FillRectangle(b, rect.X + 110, rect.Y + 5,
rect.Width - 10, rect.Height - 10);
}
}
This is my drawItem method
<Grid>
<ComboBox x:Name="MyComb" HorizontalAlignment="Left" Margin="66,81,0,0" VerticalAlignment="Top" Width="120" />
</Grid>
This is definition of combobox
Type colorType = typeof(System.Drawing.Color);
PropertyInfo[] propInfoList = colorType.GetProperties(BindingFlags.Static |
BindingFlags.DeclaredOnly | BindingFlags.Public);
foreach (PropertyInfo c in propInfoList)
{
MyComb.Items.Add(c.Name);
}
And here I am filling combobox with colors names and then I want to fill to combox with real colors according to the colors names.. But my draw item method is never called. I tried to create some DrawItem handler but, my combobox have no such thing... Then I read something about setting a DrawMode property of combobox, but my combobox doesn't that kind of property at all...
I am using net framework v.4.6.1
Can please anyone tell me, what am I missing ?
Thank you very much
The biggest problem you're having is that you're trying to use code examples that were written for the Winforms API, even though you are using the WPF API. For future reference, you really need to be more careful about identifying the context of tutorials and other resources you find online, to make sure they actually apply to your scenario.
As it happens, we have a number of related questions on Stack Overflow already:
WPF ComboBox as System.Windows.Media.Colors>
WPF - Bind ComboBox Item Foreground to Its Value
Very simple color picker made of combobox
These are all potentially useful to you, but are all based on the answer to this question:
How can I list colors in WPF with XAML?
Which was originally about just displaying the names of colors, and so took a short-cut, using the <ObjectDataProvider/> element in XAML. This led to the need to use a converter in the other questions, to convert either from a string value or a PropertyInfo instance to the appropriate color or brush.
In fact, if your code is already written to use some type of MVVM approach, and especially since you've already written code-behind to retrieve the color values from the Colors type, or at least tried to (one of the problems in your code is that you are using the Winforms Color type instead of the WPF Colors type…again, in Winforms that works fine, but the WPF API follows the Code Analysis/FxCop rules more closely, and the named colors are in the Colors type), it makes sense to just stick with that and provide a direct view model data structure to which you can bind.
In this approach, rather than providing a procedural implementation of the item drawing, you provide in XAML a declarative implementation describing what each item should look like.
Here is an example…
First, some simple view model data structures:
// Very simple container class
class ColorViewModel
{
public Brush Brush { get; }
public string Name { get; }
public ColorViewModel(Brush brush, string name)
{
Brush = brush;
Name = name;
}
}
// Main view model, acts as the data context for the window
class MainViewModel : INotifyPropertyChanged
{
public IReadOnlyList<ColorViewModel> Colors { get; }
private Brush _selectedColor;
public Brush SelectedColor
{
get { return _selectedColor; }
set { _UpdateField(ref _selectedColor, value); }
}
public MainViewModel()
{
Colors = typeof(Colors).GetProperties(BindingFlags.Static | BindingFlags.Public)
.Select(p => new ColorViewModel(new SolidColorBrush((Color)p.GetValue(null)), p.Name))
.ToList().AsReadOnly();
}
public event PropertyChangedEventHandler PropertyChanged;
private void _UpdateField<T>(ref T field, T newValue, [CallerMemberName] string propertyName = null)
{
if (!EqualityComparer<T>.Default.Equals(field, newValue))
{
field = newValue;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
With those in hand, the XAML is straight-forward:
<Window x:Class="TestSO47850587ColorComboBox.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:l="clr-namespace:TestSO47850587ColorComboBox"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<l:MainViewModel/>
</Window.DataContext>
<StackPanel>
<ComboBox Width="100" ItemsSource="{Binding Colors}"
HorizontalAlignment="Left" Grid.IsSharedSizeScope="True"
SelectedValuePath="Brush" SelectedValue="{Binding SelectedColor}">
<ComboBox.ItemTemplate>
<DataTemplate DataType="{x:Type l:ColorViewModel}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="ComboBoxItem"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Name}" Background="{Binding Brush}" HorizontalAlignment="Stretch"/>
</Grid>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<Rectangle HorizontalAlignment="Stretch" Height="24" Fill="{Binding SelectedColor}"/>
</StackPanel>
</Window>
The above displays the color names, using the actual color as the background. If all you really want is a rectangle, then you can replace the <TextBlock/> element with a <Rectangle/> element, binding to its Fill property. Naturally, you can achieve other visual effects, such as a rectangle with a margin. It's just a matter of configuring your data template according to your need.
The main point here is that you should embrace the data binding approach that defines good WPF programming, and that you should definitely not mistake Winforms code examples for WPF. :)
I'm constructing my own Button with icons and text, passing as DependencyProperty colors, icon path and text. No problem so far. Here's the code for the one of the color property.
//Text Color
public static readonly DependencyProperty forColorProperty =
DependencyProperty.Register(
"forColor",
typeof(System.Windows.Media.SolidColorBrush),
typeof(AppButtonPro),
new PropertyMetadata(Colors.DarkBlue));
public System.Windows.Media.SolidColorBrush forColor
{
get { return (System.Windows.Media.SolidColorBrush)GetValue(forColorProperty);}
set { SetValue(forColorProperty, value); }
}
And the XAML code:
<ap:AppButtonPro Style="{DynamicResource AppButtonFast}"
forColor="{Binding Source={x:Static const:Colors.White}}"
backColor="{Binding Source={x:Static const:Colors.LightBlue}}"
Grid.Column="0"
Grid.Row="1"
Grid.RowSpan="1"
Grid.ColumnSpan="3"
x:Name="btScrollUp"
Click="btScrollUp_Click"
textContentString="Text"
iconContentString="pack://application:,,,/DllData;component/Appearence/down.png"
>
</ap:AppButtonPro>
I'd like to swap colors at click to enhance contrast, so I'd like to assign the foreground color to the background and viceversa. I assume I can't simply invert the binding, so I'd like to store the color values somewhere in the style and use them as local variables to play in the states.
For example here's a textblock with foreground color with binding to forColor value as declared in XAML: I'd like to change it to the value of backColor in some visualstate and the change it back to normal when needed.
<TextBlock x:Name="textContent"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Text="{Binding textContentString, RelativeSource={RelativeSource TemplatedParent}}"
Foreground="{Binding forColor, RelativeSource={RelativeSource TemplatedParent}}"/>
I want create a ToggleButton with round corners by using my CornerRadius property. As you can see in the code below, i already added a cornerRadius property to my xaml ToggleButton to pass a radius value. But i can't find a way to use this value in c# to create a ToggleButton with round corners.
C#
public static readonly DependencyProperty CornerRadiusProperty =
DependencyProperty.Register("CornerRadius", typeof(int), typeof(MyToggleButton),
new PropertyMetadata(0)); //Default CornerRadius = 0
public int CornerRadius
{
get { return (int)GetValue(CornerRadiusProperty); }
set { SetValue(CornerRadiusProperty, value); }
}
XAML
<custom:MyToggleButton Height="25" Content="Test" CornerRadius="15" />
So how can i create a toggleButton with round corners by using my property "CornerRadius"?
Would be great if someone could help me.
I wouldn't create a new control just in order to make it round - that's what templates are for and that's what makes WPF so great! You could simply define a new template for the ToggleButton.
If you insist on inheriting your own control, you'll need to define for it a new default style that will also include a control template that will have a border that uses your CornerRadius property. You can base your new template on the default control template for ToggleButton.
I have a itemscontrol with the item template set to a border, then i bind the datacontext of the listview to a list of objects that contain a bool property.
Then i added a click event handler to the border, and when detecting a click, i cast the datacontext of the border to the class and set the bool field to true.
That works as a charm, but i want the rectangle to have a specific colour when the bool field is set to true or false, so i created a IValueConverter that takes my class and returns a colour.
That works too, the rectangles are different colors based on the bool field.
I am still able to click the rectangles, but they just arent updated.
The color of the rectangle wont change.
Datatemplate from the itemscontrol itemtemplate
<DataTemplate>
<Border ToolTip="{Binding Seat.Column}" Width="25" Height="25" Margin="0,0,2,2" BorderBrush="Black" Background="{Binding Converter={StaticResource ResourceKey=SeatStateConverter}}" BorderThickness="2" Name="rectangle1" VerticalAlignment="Center" HorizontalAlignment="Center" MouseLeftButtonDown="rectangle1_MouseLeftButtonDown">
<Label Content="{Binding Occupied}" Foreground="White" FontSize="7"></Label>
</Border>
</DataTemplate>
The click event
private void rectangle1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Border item = sender as Border;
SeatState state = item.DataContext as SeatState;
state.Locked = !state.Locked;
}
my converter
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
SeatState state = value as SeatState;
if (state == null)
return null;
SolidColorBrush brush = new SolidColorBrush();
if (state.Occupied)
{
brush.Color = Color.FromRgb(172, 0,0);
}
else if (state.Locked)
{
brush.Color = Color.FromRgb(214, 65, 0);
}
else if(!state.Occupied)
{
brush.Color = Color.FromRgb(0, 172, 0);
}
return brush;
}
This works great.. untill i add the converter that converts the objects into a SolidColorBrush.
I tried all sorts of crazy stuff that should have nothing to do with my problem.
implementing the convertback method
in the IValueConverter interface
setting the binding to a two way binding
invoking the UpdateLayout
method on the ItemsControl
But nothing seemed to work.
Anyone got any ideas?
My english could be better so please ask if there is anything you want clearified =)
Thanks in advance.
I think you are binding to the SeatState object - whereas you actually need to bind to some combination of the Occupied an Locked properties?
i.e. it's not the SeatState object itself that is changing, but rather its a couple of the properties of the SeatState.
Maybe merge the properties together somehow and set this merged property as the Path for the XAML Background.
e.g. within SeatState
private bool _Locked
public bool Locked
{
get
{
return _Locked;
}
set
{
_Locked = value;
NotifyPropertyChange("Locked");
NotifyPropertyChange("LockedAndOccupied");
}
}
private bool _Occupied
public bool Occupied
{
get
{
return _Occupied;
}
set
{
_Occupied = value;
NotifyPropertyChange("Occupied");
NotifyPropertyChange("LockedAndOccupied");
}
}
public Tuple<bool, bool> LockedAndOccupied
{
get
{
return new Tuple<bool, bool>(Locked, Occupied);
}
}
then in the XAML you can bind to Path=LockedAndOccupied, Converter=...
Obviously you'll have to change the Converter code too - I'll let you do that!
Alternatively... now I've read up about it...
There is something called a MultiBinding - http://www.switchonthecode.com/tutorials/wpf-tutorial-using-multibindings - looks perfect for your needs
Something like:
<Border.Background>
<MultiBinding Converter="{StaticResource aNewConverter}">
<Binding Path="Locked"/>
<Binding Path="Occupied"/>
</MultiBinding>
</Border.Background>
I've learnt something new tonight :)
Check the Background binding... it looks like your Path is missing. I would expect to see something like...
Background="{Binding Path=., Converter={StaticResource ResourceKey=SeatStateConverter}}"
Alternately you could try setting BindsDirectlyToSource=true.
On second thought, you probably need to implement an IMultiValueConverter, and then bind each of the properties separately. That may be what you need to do to get the change notifications on each of the properties. Here is an example of an IMultiValueConverter implementation from MSDN.
Also, you may want to check your implementation of INotifyPropertyChanged... misspellings of property names will break the change notifications...
How do I programmatically change the color of an ellipse that is defined in XAML based on a variable?
Everything I've read on binding is based on collections and lists -can't I set it simply (and literally) based on the value of a string variable? string color = "red" color = "#FF0000"
It's worth pointing out that the converter the other posts reference already exists, which is why you can do <Ellipse Fill="red"> in xaml in the first place. The converter is System.Windows.Media.BrushConverter:
BrushConverter bc = new BrushConverter();
Brush brush = (Brush) bc.ConvertFrom("Red");
The more efficient way is to use the full syntax:
myEllipse.Fill = new SolidColorBrush(Colors.Red);
EDIT in response to -1 and comments:
The code above works perfectly fine in code, which is what the original question was asking about. You also don't want an IValueConverter - these are typically used for binding scenarios. A TypeConverter is the right solution here (because you're one-way converting a string to a brush). See this article for details.
Further edit (having reread Aviad's comment): you don't need to explicitly use the TypeConverter in Xaml - it's used for you. If I write this in Xaml:
<Ellipse Fill="red">
... then the runtime automagically uses a BrushConverter to turn the string literal into a brush. That Xaml is essentially converted into the equivalent longhand:
<Ellipse>
<Ellipse.Fill>
<SolidColorBrush Color="#FFFF0000" />
</Ellipse.Fill>
</Ellipse>
So you're right - you can't use it in Xaml - but you don't need to.
Even if you had a string value that you wanted to bind in as the fill, you don't need to specify the converter manually. This test from Kaxaml:
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:s="clr-namespace:System;assembly=mscorlib">
<Page.Resources>
<s:String x:Key="col">Red</s:String>
</Page.Resources>
<StackPanel>
<Ellipse Width="20" Height="20" Fill="{Binding Source={StaticResource col}}" />
</StackPanel>
</Page>
Strangely, you can't just use the StaticResource col and still have this work - but with the binding it and automatically uses the ValueConverter to turn the string into a brush.
what you will need to do is implement a custom converter to convert the colour to the brush object. Something like this...
public class ColorToBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
System.Drawing.Color col = (System.Drawing.Color)value;
Color c = Color.FromArgb(col.A, col.R, col.G, col.B);
return new System.Windows.Media.SolidColorBrush(c);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
SolidColorBrush c = (SolidColorBrush)value;
System.Drawing.Color col = System.Drawing.Color.FromArgb(c.Color.A, c.Color.R, c.Color.G, c.Color.B);
return col;
}
}
And then specify that converter in your binding
Fill="{Binding Colors.Red, Converter={StaticResource ColorToBrushConverter }"
use
System.Windows.Media
If the name of your ellipse in your XAML is my_ellipse,
write something like this:
my_ellipse.Fill = System.Windows.Media.Brushes.Red;
or this:
my_ellipse.Fill = (SolidColorBrush)new BrushConverter().ConvertFromString("#F4F4F5")
A quick work around for this (Although its not binding, and less efficient) is to check the status of an object/element and update the new/other object(s) based on the status, I'll provide a Basic Example Below.
You can do this in MVVM by getting the status of MainWindow Objects from a User Control and changing whatever you want from the MainWindow object status.
Note: this will not work for 2 themed applications and other scenarios where more than basic use case is needed. (Example: Dark Mode, Etc)
In my example, I am using data to draw a "text" on screen (FrontFog_Text, Which is why the text is using the .Fill Property in my case).
I am not using this in my application but came across this when testing a few things so I thought I would share in this thread while I search for my answer!
private void FrontFog_ToggleButton_Unchecked(object sender, RoutedEventArgs e)
{
if (((MainWindow)App.Current.MainWindow).Theme_Control.IsChecked == true)
{
FrontFog_Text.Fill = new SolidColorBrush(System.Windows.Media.Colors.White);
}
else if (((MainWindow)App.Current.MainWindow).Theme_Control.IsChecked == false)
{
FrontFog_Text.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
}
}