How to bind `Path.Data` in a resource dictionary in XAML (Silverlight) - c#

It seems it is not possible to define geometry in a ResourceDictionary in Silverlight. So I'm using Path to store some geometries. Here is the Path.xaml file:
<ResourceDictionary ///some namespaces///>
<Path x:Key="path1" Data="//some geometry//" />
<Path x:Key="path2" Data="//some geometry//" />
<Path x:Key="path3" Data="//some geometry//" />
</ResourceDictionary>
Having reference this ResourceDictionary, I want to use these geometries somewhere in a UserControl:
<Path Data = "{Binding Source={StaticResouce path1}", Path=Data}"/>
But I'm getting the following error:
Value does not fall within the expected range.
How can I get those geometries in the XAML?

Correct you can't. I came across this problem and got round it by having the path strings as properties of a class and then adding that class as a resource. For example here is the class
public class IconPaths
{
public string CircleIcon
{
get { return "M50.5,4.7500001C25.232973,4.75 4.75,25.232973 4.7500001,50.5 4.75,75.767029 25.232973,96.25 50.5,96.25 75.767029,96.25 96.25,75.767029 96.25,50.5 96.25,25.232973 75.767029,4.75 50.5,4.7500001z M50.5,0C78.390381,0 101,22.609621 101,50.5 101,78.390381 78.390381,101 50.5,101 22.609621,101 0,78.390381 0,50.5 0,22.609621 22.609621,0 50.5,0z"; }
}
public string LogIcon
{
get { return "M16.6033,19.539C18.922133,19.539 20.042,21.777275 20.042,23.919949 20.042,26.367331 18.793436,28.397999 16.5877,28.397999 14.394864,28.397999 13.149,26.334829 13.149,24.032551 13.149,21.665472 14.301367,19.539 16.6033,19.539z M5.3724453,18.578932L5.3724453,29.357607 11.370038,29.357607 11.370038,28.189699 6.7645523,28.189699 6.7645523,18.578932z M28.522547,18.46693C24.908003,18.46693 22.700978,20.817846 22.685377,24.032669 22.685377,25.711081 23.260882,27.151291 24.189095,28.045797 25.244007,29.053604 26.587723,29.469608 28.217943,29.469608 29.67366,29.469608 30.905476,29.101805 31.529183,28.877802L31.529183,23.696165 27.97814,23.696165 27.97814,24.816576 30.169766,24.816576 30.169766,28.029497C29.848162,28.189699 29.225756,28.317898 28.314345,28.317898 25.803812,28.317898 24.156695,26.703287 24.156695,23.968267 24.156695,21.265749 25.867714,19.634937 28.490048,19.634937 29.57736,19.634937 30.297468,19.84334 30.872776,20.097841L31.20888,18.963034C30.745175,18.739132,29.770062,18.46693,28.522547,18.46693z M16.666903,18.40313C13.788068,18.40313 11.661542,20.641445 11.661542,24.064671 11.661542,27.326992 13.660466,29.534107 16.506901,29.534107 19.258234,29.534107 21.510861,27.567295 21.510861,23.856268 21.510861,20.657745 19.609839,18.40313 16.666903,18.40313z M14.433776,2.6588883C12.967757,2.6588886,11.773743,3.8522573,11.773743,5.319067L11.773743,15.361408 34.872822,15.361408C35.828533,15.361408,36.603447,16.136215,36.603447,17.092621L36.603447,30.392214C36.603447,31.347221,35.828533,32.121925,34.872822,32.121925L11.773743,32.121925 11.773743,37.347263C11.773743,38.814075,12.967757,40.007481,14.433776,40.007481L35.931637,40.007481C37.397755,40.007481,38.59177,38.814075,38.59177,37.347263L38.59177,12.690889 29.754463,12.690889C29.022553,12.690889,28.424946,12.092585,28.424946,11.36008L28.424946,2.6601186 28.424946,2.6588883z M14.433776,0L29.723061,0 41.251999,11.530681 41.251999,37.347263C41.251999,40.280281,38.866474,42.667,35.931637,42.667L14.433776,42.667C11.498941,42.667,9.1135704,40.280281,9.1135704,37.347263L9.1135704,32.121925 1.7293315,32.121925C0.7749116,32.121925,1.9777951E-07,31.347221,0,30.392214L0,17.092621C1.9777951E-07,16.136215,0.7749116,15.361408,1.7293315,15.361408L9.1135704,15.361408 9.1135704,5.319067C9.1135704,2.3854568,11.498941,0,14.433776,0z"; }
}
}
And here is it called in a resource dictionary
<LocalStyles:IconPaths x:Key="IconPaths"/>
And finaly used in a path
<Path Data="{Binding Source={StaticResource IconPaths}, Path=ArrowIcon}" Height="10" Stretch="Fill" Fill="DimGray" VerticalAlignment="Center" HorizontalAlignment="Center" RenderTransformOrigin="0.5,0.5">

Related

Geometry path dependency processing

I have Custom Control Library and do icon "control". Also i have PathGeometry figures accessible by x:Key. So as example input is IconName="Icon_Close" in MainWindow.xaml, i want to equate IconName="Icon_Close" with PathGeometry figure which x:Key equals to "Icon_Close" and show icon
But i have no ideas how to process/convert it...
Icon.xaml (Generic)
<PathGeometry x:Key="Icon_Close" Figures="M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z"/>
<PathGeometry x:Key="Icon_WndMinimize" Figures="M19,13H5V11H19V13Z"/>
<PathGeometry x:Key="Icon_WndMaximize" Figures="M19,3H5C3.89,3 3,3.89 3,5V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19V5C21,3.89 20.1,3 19,3M19,5V19H5V5H19Z"/>
<Style TargetType="{x:Type local:Icon}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:Icon}">
<Viewbox Height="{TemplateBinding IconHeight}"
Width="Auto">
<Canvas Height="24"
Width="24">
<Path Fill="{TemplateBinding IconColor}"
Data="{TemplateBinding IconName}"/>
</Canvas>
</Viewbox>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Icon.cs
public class Icon : Control
{
public static readonly DependencyProperty IconNameProperty =
DependencyProperty.Register("IconName", typeof(Geometry), typeof(Icon),
new PropertyMetadata(Geometry.Empty));
public Geometry IconName
{
get { return (Geometry)GetValue(IconNameProperty); }
set { SetValue(IconNameProperty, value); }
}
static Icon()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(Icon),
new FrameworkPropertyMetadata(typeof(Icon)));
}
}
MainWindow.xaml
<uiLib:Icon IconHeight="100"
IconColor="White"
IconName="Icon_Close"/>
If you instead use a Path you can do everything your control appears to be doing with the exception of setting the data with your path.
A Path can stretch so there's no point in the viewbox.
You don't need to put a path in a canvas either, it inherits from frameworkelement.
Here's an example path.
<Path Data="{StaticResource Musketeer}"
Height="18"
Stretch="Uniform"
Fill="Black"
Margin="4,0,0,0" />
Make the height 30 and the musketeer shaped geometry would be 30 px high and retain the proportions of the geometry.
All you need is a dependency property with an onChange handler that finds that geometry out resources.
Path is sealed so you can't extend it, but you could add an attached dependency property like this:
public class Attacher : DependencyObject
{
public static readonly DependencyProperty
GeometryProperty = DependencyProperty.RegisterAttached(
"Geometry", typeof(string), typeof(Attacher), new PropertyMetadata("", GeometryChanged));
private static void GeometryChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var path = d as Path;
if (path == null)
{
return;
}
var geom = path.TryFindResource(e.NewValue.ToString()) as Geometry;
if (geom is Geometry)
{
path.Data = geom;
}
}
public static string GetGeometry(DependencyObject d)
{
return (string)d.GetValue(GeometryProperty);
}
public static void SetGeometry(DependencyObject d, string value)
{
d.SetValue(GeometryProperty, value);
}
}
You can probably think of a better name than attacher.
The way that works is it attaches the dependency property to the path.
Usage:
<Path Fill="Red"
Stretch="Fill"
local:Attacher.Geometry="BeeIcon"
/>
local is an xmlns reference to the clr namespace the attacher is in.
My beeicon is:
<Geometry x:Key="BeeIcon">
M15.551045,25.144995L16.748029,25.144995 16.249038,28.637C16.249038,28.637,15.651051,25.543997,15.551045,25.144995z M21.237988,21.152998L21.437999,21.152998C20.340014,23.049002 18.345033,24.247 16.150041,24.247 13.95404,24.247 11.959059,23.049002 10.861073,21.252997L10.96108,21.252997C15.351034,22.550002,18.943021,21.952002,21.237988,21.152998z M21.337995,14.967002L21.437999,15.067001C21.936988,15.965002,22.235997,16.962996,22.235997,18.160002L22.235997,18.658995 22.036994,18.759001C17.746037,20.653998,12.458048,19.556998,10.16308,18.858L10.063075,18.858 10.063075,18.759001 10.063075,18.160002C10.063075,17.162001,10.263086,16.164,10.761068,15.365997L10.861073,15.365997C16.150041,17.560996,20.141011,15.665,21.337995,14.967002z M16.150041,12.072998C17.746037,12.072998,19.243007,12.671997,20.340014,13.769996L20.44002,13.869003 20.340014,13.869003C17.247018,15.365997 13.356052,14.568 11.560075,14.069 12.657052,12.772003 14.353055,12.072998 16.150041,12.072998z M27.523957,8.3820033C28.821952,8.3820033 29.918929,8.6809992 30.517924,9.3789973 32.91293,12.072998 32.712918,16.663001 27.623963,15.566001 22.534976,14.468002 18.345033,11.674003 17.646031,10.875999L19.043027,10.376998C19.143001,10.376998,23.93197,8.3820033,27.523957,8.3820033z M4.5751051,8.3820033C8.0670862,8.3820033,12.957068,10.376998,12.957068,10.376998L14.353055,10.875999C13.655062,11.674003 9.4640798,14.468002 4.3751249,15.566001 -0.71285403,16.663001 -0.91286493,12.072998 1.4821384,9.3789973 2.1801321,8.5810008 3.2781166,8.3820033 4.5751051,8.3820033z M16.150041,3.2929987C18.145022,3.292999 19.64202,4.8889994 19.64202,6.7850031 19.64202,8.7809977 18.045016,10.277 16.150041,10.277 14.154051,10.277 12.657052,8.6809992 12.657052,6.7850031 12.557047,4.8889994 14.154051,3.292999 16.150041,3.2929987z M12.757057,1.0979993L13.056066,1.5960004 12.957068,1.5960004C12.857062,1.5960005 12.657052,1.4970015 12.557047,1.3970029 12.557047,1.2969969 12.657052,1.0979994 12.757057,1.0979993z M19.542016,9.6861186E-11C19.741996,-6.1625087E-08 19.840995,-6.1625087E-08 20.041005,0.099998488 20.839003,0.399002 21.237988,1.2969969 20.839003,2.0950009 20.44002,3.093002 19.342006,3.5920026 18.345033,3.1930003L18.943021,1.996002 19.043027,1.996002C19.44201,2.0950009 19.840995,1.8960036 19.940999,1.4970014 20.041005,1.1969984 19.940999,0.79800405 19.64202,0.69799812 19.342006,0.59899892 19.143001,0.69799794 18.943021,0.99800076 18.856397,1.1721237 18.921365,1.3470176 19.072932,1.4550116L19.129043,1.4886372 19.44201,1.0979993C19.542016,1.1969984 19.64202,1.2969969 19.542016,1.3970029 19.44201,1.4970015 19.342006,1.5960005 19.143001,1.5960004L19.103326,1.5960004 18.943021,1.996002C18.444032,1.7959975 18.245027,1.1969984 18.444032,0.69799812 18.644011,0.29900353 19.043027,-6.1625087E-08 19.542016,9.6861186E-11z M12.757057,9.6861186E-11C13.256047,-6.1625087E-08 13.655062,0.29900353 13.855041,0.79800428 14.054046,1.2969969 13.855041,1.8960036 13.356052,2.0950009L13.056066,1.5960004C13.256047,1.4970015 13.356052,1.2969969 13.256047,1.0979993 13.156041,0.79800405 12.857062,0.69799794 12.557047,0.79800428 12.258068,0.89800252 12.059064,1.2969969 12.258068,1.5960004 12.458048,1.996002 12.857062,2.1949994 13.156041,2.0950009L13.256047,2.0950009 13.855041,3.1930003C12.857062,3.5920026 11.759047,3.093002 11.360063,2.0950009 11.061054,1.2969969 11.460069,0.399002 12.158062,0.099998488 12.358073,-6.1625087E-08 12.557047,-6.1625087E-08 12.757057,9.6861186E-11z
</Geometry>
But it also works fine with your style of defining streamgeometries.
<Path Fill="Red"
Stretch="Uniform"
Height="32"
local:Attacher.Geometry="Icon_Close"
/>
You can then bind fill, stroke, height, stretch etc and a string for the geometry.

WPF DataContext works differently in seemingly identical situations

I have the following resources:
<Window.Resources>
<SolidColorBrush x:Key="b" Color="{Binding B}" />
<my:C x:Key="c" Prop="{Binding Source={StaticResource b}}" />
<my:C x:Key="d" Prop="{Binding A}" />
<Ellipse x:Key="e" Fill="{Binding A}" />
<Ellipse x:Key="f">
<Ellipse.Fill>
<SolidColorBrush Color="{Binding B}" />
</Ellipse.Fill>
</Ellipse>
</Window.Resources>
My window has a data context declared like this:
<Window ... DataContext="{my:Context}" ...>
Custom classes C and Context are defined like this:
public class Context : MarkupExtension
{
public Brush A { get; } = Brushes.Blue;
public Color B { get; } = Colors.Red;
public override object ProvideValue(IServiceProvider serviceProvider) => this;
}
public class C : DependencyObject
{
public static readonly DependencyProperty PropProperty = DependencyProperty.Register("Prop", typeof(Brush), typeof(C));
public Brush Prop { get { return (Brush)GetValue(PropProperty); } set { SetValue(PropProperty, value); } }
}
Now, the ways in which I use my data context and binding seem very similar to me, yet if I check my resources with the following code (inside a button click handler)
MessageBox.Show("f: " + ((FindResource("f") as Ellipse).Fill?.ToString() ?? "null"));
MessageBox.Show("e: " + ((FindResource("e") as Ellipse).Fill?.ToString() ?? "null"));
MessageBox.Show("d: " + ((FindResource("d") as C).Prop?.ToString() ?? "null"));
MessageBox.Show("c: " + ((FindResource("c") as C).Prop?.ToString() ?? "null"));
MessageBox.Show("b: " + (FindResource("b") as SolidColorBrush).Color.ToString());
I get this result:
f: #00FFFFFF
e: null
d: null
c: #FFFF0000
b: #FFFF0000
i.e. only the last two are seemingly correct. What could be the reason for this?
Strange.
my:C has obviously no DataContext and can therefore not bind directly to anything.
Resources with DataContext do not inherit the resources owner's DataContext (Ellipses e and f)
SolidColorBrush "b" derive form System.Windows.Freezable which has a protected Field/Property called InheritanceContext which for "b" is set to the MainWindow. I think it has access to the Context.B through this reference and that's why "b" and "c" shows the right color.
I was curious about this, and so decided to play around with it a little. I am nowhere near an expert on XAML, but I wanted to share my findings in case it helps out at all.
I added the following XAML to a Grid on the page:
<Ellipse Fill="{StaticResource b}" />
<Ellipse Grid.Row="1" Fill="{Binding Source={StaticResource c}, Path=Prop}" />
<Ellipse Grid.Row="2" Fill="{Binding Source={StaticResource d}, Path=Prop}" />
<ContentControl Grid.Row="3" Content="{StaticResource e}" />
<ContentControl Grid.Row="4" Content="{StaticResource f}" />
Here is a screenshot of the results:
The following binding error appeared in the Output window, which I think explains why d is not filled:
System.Windows.Data Error: 2 : Cannot find governing FrameworkElement
or FrameworkContentElement for target element.
BindingExpression:Path=A; DataItem=null; target element is 'C'
(HashCode=60275915); target property is 'Prop' (type 'Brush')
It looks like it may be having trouble resolving the binding for d because it can't locate its position in the element hierarchy, and so can't resolve the DataContext.
I also noticed that if I commented the XAML out, the behavior was exactly the same as was posted in the question. Both e and d were null. Based on this, it seems like the usage of the resources may impact whether or not the binding can be resolved at runtime.
It would be great to hear from someone with more insight into the internal workings of how bindings function in resources.

Convert Shape into reusable Geometry in WPF

I am trying to convert a System.Windows.Shapes.Shape object into a System.Windows.Media.Geometry object.
With the Geometry object, I am going to render it multiple times with a custom graph control depending on a set of data points. This requires that each instance of the Geometry object has a unique TranslateTransform object.
Now, I am approaching the issue in two different ways, but neither seems to be working correctly. My custom control uses the following code in order to draw the geometry:
//Create an instance of the geometry the shape uses.
Geometry geo = DataPointShape.RenderedGeometry.Clone();
//Apply transformation.
TranslateTransform translation = new TranslateTransform(dataPoint.X, dataPoint.Y);
geo.Transform = translation;
//Create pen and draw geometry.
Pen shapePen = new Pen(DataPointShape.Stroke, DataPointShape.StrokeThickness);
dc.DrawGeometry(DataPointShape.Fill, shapePen, geo);
I have also tried the following alternate code:
//Create an instance of the geometry the shape uses.
Geometry geo = DataPointShape.RenderedGeometry;
//Apply transformation.
TranslateTransform translation = new TranslateTransform(dataPoint.X, dataPoint.Y);
dc.PushTransform(translation);
//Create pen and draw geometry.
Pen shapePen = new Pen(DataPointShape.Stroke, DataPointShape.StrokeThickness);
dc.DrawGeometry(DataPointShape.Fill, shapePen, geo);
dc.Pop(); //Undo translation.
The difference is that the second snippet doesn't clone or modify the Shape.RenderedGeometry property.
Oddly enough, I occasionally can view the geometry used for the data points in the WPF designer. However, the behavior is inconsistent and difficult to figure out how to make the geometry always appear. Also, when I execute my application, the data points never appear with the specified geometry.
EDIT: I have figured out how to generate the appearance of the geometry. But this only works in design-mode. Execute these steps:
Rebuild project.
Go to MainWindow.xaml and click in the custom shape object so that the shape's properties load into Visual Studio's property window. Wait until the property window renders what the shape looks like.
Modify the data points collection or properties to see the geometry rendered properly.
Here is what I want the control to ultimately look like for now:
How can I convert a Shape object to a Geometry object for rendering multiple times?
Your help is tremendously appreciated!
Let me give the full context of my problem, as well as all necessary code to understanding how my control is set up. Hopefully, this might indicate what problems exist in my method of converting the Shape object to a Geometry object.
MainWindow.xaml
<Window x:Class="CustomControls.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:CustomControls">
<Grid>
<local:LineGraph>
<local:LineGraph.DataPointShape>
<Ellipse Width="10" Height="10" Fill="Red" Stroke="Black" StrokeThickness="1" />
</local:LineGraph.DataPointShape>
<local:LineGraph.DataPoints>
<local:DataPoint X="10" Y="10"/>
<local:DataPoint X="20" Y="20"/>
<local:DataPoint X="30" Y="30"/>
<local:DataPoint X="40" Y="40"/>
</local:LineGraph.DataPoints>
</local:LineGraph>
</Grid>
DataPoint.cs
This class just has two DependencyProperties (X & Y) and it gives a notification when any of those properties are changed. This notification is used to trigger a re-render via UIElement.InvalidateVisual().
public class DataPoint : DependencyObject, INotifyPropertyChanged
{
public static readonly DependencyProperty XProperty = DependencyProperty.Register("XProperty", typeof(double), typeof(DataPoint), new FrameworkPropertyMetadata(0.0d, DataPoint_PropertyChanged));
public static readonly DependencyProperty YProperty = DependencyProperty.Register("YProperty", typeof(double), typeof(DataPoint), new FrameworkPropertyMetadata(0.0d, DataPoint_PropertyChanged));
private static void DataPoint_PropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
DataPoint dp = (DataPoint)sender;
dp.RaisePropertyChanged(e.Property.Name);
}
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
public double X
{
get { return (double)GetValue(XProperty); }
set { SetValue(XProperty, (double)value); }
}
public double Y
{
get { return (double)GetValue(YProperty); }
set { SetValue(YProperty, (double)value); }
}
}
LineGraph.cs
This is the control. It contains the collection of data points and provides mechanisms for re-rendering the data points (useful for WPF designer). Of particular importance is the logic posted above which is inside of the UIElement.OnRender() method.
public class LineGraph : FrameworkElement
{
public static readonly DependencyProperty DataPointShapeProperty = DependencyProperty.Register("DataPointShapeProperty", typeof(Shape), typeof(LineGraph), new FrameworkPropertyMetadata(default(Shape), FrameworkPropertyMetadataOptions.AffectsRender, DataPointShapeChanged));
public static readonly DependencyProperty DataPointsProperty = DependencyProperty.Register("DataPointsProperty", typeof(ObservableCollection<DataPoint>), typeof(LineGraph), new FrameworkPropertyMetadata(default(ObservableCollection<DataPoint>), FrameworkPropertyMetadataOptions.AffectsRender, DataPointsChanged));
private static void DataPointShapeChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
LineGraph g = (LineGraph)sender;
g.InvalidateVisual();
}
private static void DataPointsChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{ //Collection referenced set or unset.
LineGraph g = (LineGraph)sender;
INotifyCollectionChanged oldValue = e.OldValue as INotifyCollectionChanged;
INotifyCollectionChanged newValue = e.NewValue as INotifyCollectionChanged;
if (oldValue != null)
oldValue.CollectionChanged -= g.DataPoints_CollectionChanged;
if (newValue != null)
newValue.CollectionChanged += g.DataPoints_CollectionChanged;
//Update the point visuals.
g.InvalidateVisual();
}
private void DataPoints_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{ //Collection changed (added/removed from).
if (e.OldItems != null)
foreach (INotifyPropertyChanged n in e.OldItems)
{
n.PropertyChanged -= DataPoint_PropertyChanged;
}
if (e.NewItems != null)
foreach (INotifyPropertyChanged n in e.NewItems)
{
n.PropertyChanged += DataPoint_PropertyChanged;
}
InvalidateVisual();
}
private void DataPoint_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
//Re-render the LineGraph when a DataPoint has a property that changes.
InvalidateVisual();
}
public Shape DataPointShape
{
get { return (Shape)GetValue(DataPointShapeProperty); }
set { SetValue(DataPointShapeProperty, (Shape)value); }
}
public ObservableCollection<DataPoint> DataPoints
{
get { return (ObservableCollection<DataPoint>)GetValue(DataPointsProperty); }
set { SetValue(DataPointsProperty, (ObservableCollection<DataPoint>)value); }
}
public LineGraph()
{ //Provide instance-specific value for data point collection instead of a shared static instance.
SetCurrentValue(DataPointsProperty, new ObservableCollection<DataPoint>());
}
protected override void OnRender(DrawingContext dc)
{
if (DataPointShape != null)
{
Pen shapePen = new Pen(DataPointShape.Stroke, DataPointShape.StrokeThickness);
foreach (DataPoint dp in DataPoints)
{
Geometry geo = DataPointShape.RenderedGeometry.Clone();
TranslateTransform translation = new TranslateTransform(dp.X, dp.Y);
geo.Transform = translation;
dc.DrawGeometry(DataPointShape.Fill, shapePen, geo);
}
}
}
}
EDIT 2:In response to this answer by Peter Duniho, I would like to provide the alternate method to lying to Visual Studio in creating a custom control. For creating the custom control execute these steps:
Create folder in root of project named Themes
Create resource dictionary in Themes folder named Generic.xaml
Create a style in the resource dictionary for the control.
Apply the style from the control's C# code.
Generic.xamlHere is an example of for the SimpleGraph described by Peter.
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:CustomControls">
<Style TargetType="local:SimpleGraph" BasedOn="{StaticResource {x:Type ItemsControl}}">
<Style.Resources>
<EllipseGeometry x:Key="defaultGraphGeometry" Center="5,5" RadiusX="5" RadiusY="5"/>
</Style.Resources>
<Style.Setters>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<Canvas IsItemsHost="True"/>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate DataType="{x:Type local:DataPoint}">
<Path Fill="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:SimpleGraph}}, Path=DataPointFill}"
Stroke="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:SimpleGraph}}, Path=DataPointStroke}"
StrokeThickness="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:SimpleGraph}}, Path=DataPointStrokeThickness}"
Data="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:SimpleGraph}}, Path=DataPointGeometry}">
<Path.RenderTransform>
<TranslateTransform X="{Binding X}" Y="{Binding Y}"/>
</Path.RenderTransform>
</Path>
</DataTemplate>
</Setter.Value>
</Setter>
</Style.Setters>
</Style>
</ResourceDictionary>
Lastly, apply the style like so in the SimpleGraph constructor:
public SimpleGraph()
{
DefaultStyleKey = typeof(SimpleGraph);
DataPointGeometry = (Geometry)FindResource("defaultGraphGeometry");
}
I think that you are probably not approaching this in the best way. Based on the code you posted, it seems that you are trying to do manually things that WPF is reasonably good at handling automatically.
The main tricky part (at least for me…I'm hardly a WPF expert) is that you appear to want to use an actual Shape object as the template for your graph's data point graphics, and I'm not entirely sure of the best way to allow for that template to be replaced programmatically or declaratively without exposing the underlying transformation mechanic that controls the positioning on the graph.
So here's an example that ignores that particular aspect (I will comment on alternatives below), but which I believe otherwise serves your precise needs.
First, I create a custom ItemsControl class (in Visual Studio, I do this by lying and telling VS I want to add a UserControl, which gets me a XAML-based item in the project…I immediately replace "UserControl" with "ItemsControl" in both the .xaml and .xaml.cs files):
XAML:
<ItemsControl x:Class="TestSO28332278SimpleGraphControl.SimpleGraph"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:TestSO28332278SimpleGraphControl"
mc:Ignorable="d"
x:Name="root"
d:DesignHeight="300" d:DesignWidth="300">
<ItemsControl.Resources>
<EllipseGeometry x:Key="defaultGraphGeometry" Center="5,5" RadiusX="5" RadiusY="5" />
</ItemsControl.Resources>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas IsItemsHost="True" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type local:DataPoint}">
<Path Data="{Binding ElementName=root, Path=DataPointGeometry}"
Fill="Red" Stroke="Black" StrokeThickness="1">
<Path.RenderTransform>
<TranslateTransform X="{Binding X}" Y="{Binding Y}"/>
</Path.RenderTransform>
</Path>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
C#:
public partial class SimpleGraph : ItemsControl
{
public Geometry DataPointGeometry
{
get { return (Geometry)GetValue(DataPointShapeProperty); }
set { SetValue(DataPointShapeProperty, value); }
}
public static DependencyProperty DataPointShapeProperty = DependencyProperty.Register(
"DataPointGeometry", typeof(Geometry), typeof(SimpleGraph));
public SimpleGraph()
{
InitializeComponent();
DataPointGeometry = (Geometry)FindResource("defaultGraphGeometry");
}
}
The key here is that I have an ItemsControl class with a default ItemTemplate that has a single Path object. That object's geometry is bound to the controls DataPointGeometry property, and its RenderTransform is bound to the data item's X and Y values as offsets for a translation transform.
A simple Canvas is used for the ItemsPanel, as I just need a place to draw things, without any other layout features. Finally, there is a resource defining a default geometry to use, in case the caller doesn't provide one.
And about that caller…
Here is a simple example of how one might use the above:
<Window x:Class="TestSO28332278SimpleGraphControl.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestSO28332278SimpleGraphControl"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<PathGeometry x:Key="dataPointGeometry"
Figures="M 0.5000,0.0000
L 0.6176,0.3382
0.9755,0.3455
0.6902,0.5618
0.7939,0.9045
0.5000,0.7000
0.2061,0.9045
0.3098,0.5618
0.0245,0.3455
0.3824,0.3382 Z">
<PathGeometry.Transform>
<ScaleTransform ScaleX="20" ScaleY="20" />
</PathGeometry.Transform>
</PathGeometry>
</Window.Resources>
<Grid>
<Border Margin="3" BorderBrush="Black" BorderThickness="1">
<local:SimpleGraph Width="450" Height="300" DataPointGeometry="{StaticResource dataPointGeometry}">
<local:SimpleGraph.Items>
<local:DataPoint X="10" Y="10" />
<local:DataPoint X="25" Y="25" />
<local:DataPoint X="40" Y="40" />
<local:DataPoint X="55" Y="55" />
</local:SimpleGraph.Items>
</local:SimpleGraph>
</Border>
</Grid>
</Window>
In the above, the only truly interesting thing is that I declare a PathGeometry resource, and then bind that resource to the control's DataPointGeometry property. This allows the program to provide a custom geometry for the graph.
WPF handles the rest through implicit data binding and templating. If the values of any of the DataPoint objects change, or the data collection itself is modified, the graph will be updated automatically.
Here's what it looks like:
I will note that the above example only allows you to specify the geometry. The other shape attributes are hard-coded in the data template. This seems slightly different from what you asked to do. But note that you have a few alternatives here that should address your need without requiring the reintroduction of all the extra manual-binding/updating code in your example:
Simply add other properties, bound to the template Path object in a fashion similar to the DataPointGeometry property. E.g. DataPointFill, DataPointStroke, etc.
Go ahead and allow the user to specify a Shape object, and then use the properties of that object to populate specific properties bound to the properties of the template object. This is mainly a convenience to the caller; if anything, it's a bit of added complication in the graph control itself.
Go whole-hog and allow the user to specify a Shape object, which you then convert to a template by using XamlWriter to create some XAML for the object, add the necessary Transform element to the XAML and wrap it in a DataTemplate declaration (e.g. by loading the XAML as an in-memory DOM to modify the XAML), and then using XamlReader to then load the XAML as a template which you can then assign to the ItemTemplate property.
Option #3 seems the most complicated to me. So complicated in fact that I did not bother to prototype an example using it…I did a little research and it seems to me that it should work, but I admit that I did not verify for myself that it does. But it would certainly be the gold standard in terms of absolute flexibility for the caller.

WPF. FormatException when binding an ImageBrush Viewbox property to an object

I'm trying to bind the "Viewbox" property of an ImageBrush to a class property at code-behind.
I have two images, the idea is that while i move the mouse over the top image, the bottom one shows a part of the top image in a Viewbox, relative to the mouse position.
The code is just for testing while i'm learning WPF, so i know it could be much better, sorry.
XAML Code:
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Title="MainWindow" Height="950" Width="525">
...
<Rectangle Grid.Row="0" MouseMove="Rectangle_MouseMove">
<Rectangle.Fill>
<ImageBrush Stretch="UniformToFill" ImageSource="descarga.png"/>
</Rectangle.Fill>
</Rectangle>
<Rectangle Grid.Row="1">
<Rectangle.Fill>
<ImageBrush Stretch="UniformToFill" ImageSource="descarga.png" ViewboxUnits="Absolute" Viewbox="{Binding Source=ViewboxRect}"/>
</Rectangle.Fill>
</Rectangle>
C# Code behind:
private Rect _rect;
public MainWindow()
{
InitializeComponent();
}
public Rect ViewboxRect
{
get
{
return _rect;
}
set
{
_rect = value;
}
}
private void Rectangle_MouseMove(object sender, MouseEventArgs e)
{
Point p = e.GetPosition(this);
_rect.X = p.X;
_rect.Y = p.Y;
_rect.Width = p.X + 10;
_rect.Height = p.Y + 10;
}
The code above throws the following exception:
System.Windows.Data Error: 6 : 'TargetDefaultValueConverter' converter failed to convert value 'ViewboxRect' (type 'String'); fallback value will be used, if available. BindingExpression:Path=; DataItem='String' (HashCode=1651705780); target element is 'ImageBrush' (HashCode=47805141); target property is 'Viewbox' (type 'Rect') FormatException:'System.FormatException: input string was not in a correct format.
I've tried to change"_rect" to a String, but the same error is thrown.
Why does the error says "converter failed to convert value 'ViewboxRect' (type 'String')" while that property is a Rect and not a String?
Thank you.
In my opinion, your binding does not seem to be right. Your are binding to a MainWindow's property so it should be:
<Rectangle Grid.Row="1">
<Rectangle.Fill>
<ImageBrush Stretch="UniformToFill" ImageSource="descarga.png" ViewboxUnits="Absolute"
Viewbox="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:MainWindow}}, Path=ViewboxRect}"/>
</Rectangle.Fill>
</Rectangle>
Moreover you should consider that Rect does not implement INotifyPropertyChanged, so your UI will be not aware about changements you make in your Rectangle_MouseMove method.

Using Vector Graphics as Icon in WPF

I have the following base class for MenuItems in my MVVM application
public class StandardMenuItem : MenuItemBase, IExecutableItem
{
...
public Image Icon { get; private set; }
...
}
where my initial idea was to use Image to back the icons I display on my MenuItems. I have now come to the point where I am starting to use these MenuItems in the front end of my application and have found a superb vector graphics library I want to use instead.
<ResourceDictionary x:Class="resources_icons_xaml"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas x:Key="appbar_acorn" Width="48" Height="48" Clip="F1 M 0,0L 48,0L 48,48L 0,48L 0,0">
<Path Width="22.3248" Height="25.8518" Canvas.Left="13.6757" Canvas.Top="11.4012" Stretch="Fill" Fill="{DynamicResource BlackBrush}" Data="F1 M 16.6309,18.6563C 17.1309,8.15625 29.8809,14.1563 29.8809,14.1563C 30.8809,11.1563 34.1308,11.4063 34.1308,11.4063C 33.5,12 34.6309,13.1563 34.6309,13.1563C 32.1309,13.1562 31.1309,14.9062 31.1309,14.9062C 41.1309,23.9062 32.6309,27.9063 32.6309,27.9062C 24.6309,24.9063 21.1309,22.1562 16.6309,18.6563 Z M 16.6309,19.9063C 21.6309,24.1563 25.1309,26.1562 31.6309,28.6562C 31.6309,28.6562 26.3809,39.1562 18.3809,36.1563C 18.3809,36.1563 18,38 16.3809,36.9063C 15,36 16.3809,34.9063 16.3809,34.9063C 16.3809,34.9063 10.1309,30.9062 16.6309,19.9063 Z "/>
</Canvas>
...
<ResourceDictionary/>
My problem is, using these vector graphics via code does not seem straight forward. I know how to include such graphics in XAML
<!-- Include Resource Dictionary -->
<MenuItem Header="Show Difference Details"
ToolTip="Launch the grouped data file and analysis window."
IsEnabled="{Binding GroupedDataIsDifferent}"
Caliburn:Message.Attach="[Event Click] = [Action ShowDifferenceDetailsAsync()]">
<MenuItem.Icon>
<Rectangle Width="16" Height="16">
<Rectangle.Fill>
<VisualBrush Stretch="Uniform" Visual="{StaticResource appbar_column_two}" />
</Rectangle.Fill>
</Rectangle>
</MenuItem.Icon>
</MenuItem>
but this is not my problem. My questions are:
How can I use vector graphics from a resource dictionary in my Icons/Images for my StandardMenuItems?
If the answer to 1. is "you can't", how can I convert from a vector graphic to an Icon in code?
Thanks for your time.
Edit. I want to be able to pick up the graphics using code. So for my menu item I have a method
public StandardMenuItem WithIcon(Assembly source, string path)
{
var manager = IoC.Get<IResourceManager>();
var iconSource = manager.GetBitmap(path, source.GetAssemblyName());
if (source != null)
{
IconSource = path;
}
return this;
}
my issue now is getting the correct path to the vector image I want. Lets say in my solution I have my vector image in "Graphics/Icons.xaml" and the resource is called "appbar_acorn", how can I reference this?
here you go
start by changing the Icon property to string
eg
public string Icon { get; private set; }
assign the icon value as key of the icon you want to use
Icon = "appbar_acorn";
define the converter in resources
<l:StringToResourceConverter x:Key="StringToResourceConverter" />
l: refers to the converter's namespace eg xmlns:l="clr-namespace:CSharpWPF"
the usage
<MenuItem Icon="{Binding Icon,Converter={StaticResource StringToResourceConverter}}"
Header="Menu"/>
result
here is the converter class
namespace CSharpWPF
{
class StringToResourceConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return Application.Current.FindResource(value);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
you may need to adjust the icon size and placement on canvas, in the sample above I removed the Canvas.Left="13.6757" & Canvas.Top="11.4012" but still it is little big for the menu icon

Categories