How to bind to an unbindable property without violating MVVM? - c#

I am using SharpVector's SvgViewBox to show static resource images like this:
<svgc:SvgViewbox Source="/Resources/label.svg"/>
which works fine. However, I wish to control what image is shown through a binding to a view model.
The problem I'm experiencing is that the Source property of SvgViewbox is not bindable.
How can I get around this limitation without violating MVVM (e.g., passing the control into the view model and modifying it there)?

What you are looking for is called attached properties. MSDN offers a topic on it with the title "Custom Attached Properties"
In your case it may look as simple as this
namespace MyProject.Extensions
{
public class SvgViewboxAttachedProperties : DependencyObject
{
public static string GetSource(DependencyObject obj)
{
return (string) obj.GetValue(SourceProperty);
}
public static void SetSource(DependencyObject obj, string value)
{
obj.SetValue(SourceProperty, value);
}
private static void OnSourceChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var svgControl = obj as SvgViewbox;
if (svgControl != null)
{
var path = (string)e.NewValue;
svgControl.Source = string.IsNullOrWhiteSpace(path) ? default(Uri) : new Uri(path);
}
}
public static readonly DependencyProperty SourceProperty =
DependencyProperty.RegisterAttached("Source",
typeof (string), typeof (SvgViewboxAttachedProperties),
// default value: null
new PropertyMetadata(null, OnSourceChanged));
}
}
XAML to use it
<SvgViewbox Margin="0 200"
local:SvgViewboxAttachedProperties.Source="{Binding Path=ImagePath}" />
Note that local is the namespace prefix and it should point to your assembly/namespace where that class is located at, i.e. xmlns:local="clr-namespace:MyProject.Extensions;assembly=MyProject".
Then only use your attached property (local:Source) and never the Source property.
The new attached property local:Source is of type System.Uri. To update the image first assign null then the filename/filepath again.

Related

Dependency Property Call in code behind

I have created a custom UserControl with some Dependency properties.
This custom control is hosted on a Window.
When I try to get a value from a DependecyProperty in code behind it doesn't work.
public static readonly DependencyProperty ValueDp = DependencyProperty.Register("Value", typeof(string), typeof(MyCustomUserControl), new FrameworkPropertyMetadata(string.Empty, OutputHandler));
public string Value
{
get { return (string)GetValue(ValueDp); }
set { SetValue(ValueDp, value); }
}
private static void OutputHandler(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
var temp= dependencyObject as MyCustomUserControl;
if (temp!= null)
{
dependencyObject.SetValue(ValueDp,temp._conversionValue);
}
}
On the host I have put a button and when I click on it, I want to read the value stored in the DP, but I will always get the default value set in DP.
Any ideas what I`m doing wrong here?
Regards
I think that in the OutputHandler method you are always discarding the new value assigned to the property (dependencyPropertyChangedEventArgs.NewValue)
As #Alberto has said the OldValue and NewValue are the properties which hold the value of the DependencyProperty. The above properties are found in dependencyPropertyChangedEventArgs. In your Handler the member dependencyObject and temp refer to the same object.

Global Scope Attached Dependency Property

I would like to do something like a static variable in normal programming, only in XAML using Dependency Properties.
Meaning I would like the property to :
Be one instance
Be visible by every element
Be bindable
How do I do that ?
It sounds like you want an attached property that always applies to every element. I think the easiest way to make that work would be through the CoerceValueCallback of the dependency property, where you could force it to always return the static value regardless of the element's local value (you would update the static value in the PropertyChangedCallback).
This seems like an odd way to use the dependency property system, though. Maybe you just need a central binding source? You can bind to a static instance by assigning Binding.Source using x:Static:
{Binding Source={x:Static Member=global:GlobalObject.SharedInstance},
Path=SharedValue}
Note that SharedValue isn't a static property; it's a property of an instance accessed from the static SharedInstance property:
public class GlobalObject {
private static readonly GlobalObject _instance = new GlobalObject();
public static GlobalObject SharedInstance { get { return _instance; } }
public object SharedValue { get; set; }
}
Easy.
Create an attached DependencyProperty on the DependencyObject Type.
public static readonly DependencyProperty DerpProperty =
DependencyProperty.RegisterAttached(
"Derp",
typeof(DependencyObject),
typeof(Herp),
new FrameworkPropertyMetadata());
public static void SetDerp(DependencyObject element, Herp value)
{
element.SetValue(DerpProperty, value);
}
public static Herp GetDerp(DependencyObject element)
{
return (Herp)element.GetValue(DerpProperty);
}
Defined on any type, it can be used on any type as well. In this example, it creates a new property called Derp on all DependencyObject instances that gets/sets an associated Herp value.
Assuming this is defined in a type called LolKThx in the namespace WpfFtw, you might use it in this way...
<Textblock
xmlns:lol="clr-namespace:WpfFtw"
lol:LolKThx.Derp="There's an implicit conversion for string -> Herp, btw" />
You can specify callbacks in your FrameworkPropertyMetadata to perform any action you need on setting/getting values.

Why this property isn't visible? Says attachable property can't be found

I'm creating Behavior with attached properties. Behavior should attach to Grid:
public class InteractionsBehavior : Behavior<Grid>
{
public static readonly DependencyProperty ContainerProperty =
DependencyProperty.RegisterAttached("Container", typeof(Grid), typeof(Grid), new PropertyMetadata(null));
public static readonly DependencyProperty InteractionsProviderProperty =
DependencyProperty.RegisterAttached("InteractionsProvider", typeof(IInteractionsProvider), typeof(Grid), new PropertyMetadata(null, OnInteractionsProviderPropertyChanged));
public Grid Container
{
get { return GetValue(ContainerProperty) as Grid; }
set { this.SetValue(ContainerProperty, value); }
}
public IInteractionsProvider InteractionsProvider
{
get { return GetValue(InteractionsProviderProperty) as IInteractionsProvider; }
set { this.SetValue(InteractionsProviderProperty, value); }
}
Now when I'm writing XAML like this I get error:
<Grid Background="White" x:Name="LayoutRoot"
Behaviors:InteractionsBehavior.InteractionsProvider="{Binding InteractionsProvider}">
Error 4 The property 'InteractionsProvider' does not exist on the type
'Grid' in the XML namespace
'clr-namespace:Infrastructure.Behaviors;assembly=Infrastructure.SL'. C:\MainPage.xaml 11 11 Controls.SL.Test
Error 1 The attachable property 'InteractionsProvider' was not found
in type
'InteractionsBehavior'. C:\MainPage.xaml 11 11 Controls.SL.Test
You specified that it only should be available to be attached ("owned") by an InteractionsBehavior. If you want to be able to assign this to a grid, change the RegisterAttached line to:
public static readonly DependencyProperty InteractionsProviderProperty =
DependencyProperty.RegisterAttached("InteractionsProvider", typeof(IInteractionsProvider), typeof(Grid), new PropertyMetadata(null, OnInteractionsProviderPropertyChanged));
(Or use some base class in Grid's class hierarchy...)
The problem is in the declaration of your attached property. Attached properties have 4 parts: the name, the type, the owner type, and the property metadata. You're specifying that the InteractionsProvider property is owned (and thus supplied) by the type Grid. That's not actually the case. Change the owner type (third parameter) to typeof(InteractionsBehavior) (the class in which you've declared the attached property), switch to static get/set methods instead of a property (because you're using an attached property, not a dependency property), and it should all work as you expect.

Wrapped WPF Control

I'm trying to create a GUI (WPF) Library where each (custom) control basically wraps an internal (third party) control. Then, I'm manually exposing each property (not all of them, but almost). In XAML the resulting control is pretty straightforward:
<my:CustomButton Content="ClickMe" />
And the code behind is quite simple as well:
public class CustomButton : Control
{
private MyThirdPartyButton _button = null;
static CustomButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomButton), new FrameworkPropertyMetadata(typeof(CustomButton)));
}
public CustomButton()
{
_button = new MyThirdPartyButton();
this.AddVisualChild(_button);
}
protected override int VisualChildrenCount
{
get
{ return _button == null ? 0 : 1; }
}
protected override Visual GetVisualChild(int index)
{
if (_button == null)
{
throw new ArgumentOutOfRangeException();
}
return _button;
}
#region Property: Content
public Object Content
{
get { return GetValue(ContentProperty); }
set { SetValue(ContentProperty, value); }
}
public static readonly DependencyProperty ContentProperty = DependencyProperty.Register(
"Content", typeof(Object),
typeof(CustomButton),
new FrameworkPropertyMetadata(new PropertyChangedCallback(ChangeContent))
);
private static void ChangeContent(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
(source as CustomButton).UpdateContent(e.NewValue);
}
private void UpdateContent(Object sel)
{
_button.Content = sel;
}
#endregion
}
The problem comes after we expose MyThirdPartyButton as a property (in case we don't expose something, we would like to give the programmer the means to use it directly). By simply creating the property, like this:
public MyThirdPartyButton InternalControl
{
get { return _button; }
set
{
if (_button != value)
{
this.RemoveVisualChild(_button);
_button = value;
this.AddVisualChild(_button);
}
}
}
The resulting XAML would be this:
<my:CustomButton>
<my:CustomButton.InternalControl>
<thirdparty:MyThirdPartyButton Content="ClickMe" />
</my:CustomButton.InternalControl>
And what I'm looking for, is something like this:
<my:CustomButton>
<my:CustomButton.InternalControl Content="ClickMe" />
But (with the code I have) its impossible to add attributes to InternalControl...
Any ideas/suggestions?
Thanks a lot,
--
Robert
WPF's animation system has the ability to set sub-properties of objects, but the XAML parser does not.
Two workarounds:
In the InternalControl property setter, take the value passed in and iterate through its DependencyProperties copying them to your actual InternalControl.
Use a build event to programmatically create attached properties for all internal control properties.
I'll explain each of these in turn.
Setting properties using the property setter
This solution will not result in the simplified syntax you desire, but it is simple to implement and will probably solve the main problem with is, how to merge values set on your container control with values set on the internal control.
For this solution you continue to use the XAML you didn't like:
<my:CustomButton Something="Abc">
<my:CustomButton.InternalControl>
<thirdparty:MyThirdPartyButton Content="ClickMe" />
</my:CustomButton.InternalControl>
but you don't actually end up replacing your InternalControl.
To do this, your InternalControl's setter would be:
public InternalControl InternalControl
{
get { return _internalControl; }
set
{
var enumerator = value.GetLocalValueEnumerator();
while(enumerator.MoveNext())
{
var entry = enumerator.Current as LocalValueEntry;
_internalControl.SetValue(entry.Property, entry.Value);
}
}
}
You may need some additional logic to exclude DPs not publically visible or that are set by default. This can actually be handled easily by creating a dummy object in the static constructor and making a list of DPs that have local values by default.
Using a build event to create attached properties
This solution allows you to write very pretty XAML:
<my:CustomButton Something="Abc"
my:ThirdPartyButtonProperty.Content="ClickMe" />
The implementation is to automatically create the ThirdPartyButtonProperty class in a build event. The build event will use CodeDOM to construct attached properties for each property declared in ThirdPartyButton that isn't already mirrored in CustomButton. In each case, the PropertyChangedCallback for the attached property will copy the value into the corresponding property of InternalControl:
public class ThirdPartyButtonProperty
{
public static object GetContent(...
public static void SetContent(...
public static readonly DependencyProperty ContentProperty = DependencyProperty.RegisterAttached("Content", typeof(object), typeof(ThirdPartyButtonProperty), new PropertyMetadata
{
PropertyChangedCallback = (obj, e) =>
{
((CustomButton)obj).InternalControl.Content = (object)e.NewValue;
}
});
}
This part of the implementation is straightforward: The tricky part is creating the MSBuild task, referencing it from your .csproj, and sequencing it so that it runs after the precompile of my:CustomButton so it can see what additional properties it needs to add.

Variable Bindings in WPF

I’m creating a UserControl for a rich TreeView (one that has context menus for renaming nodes, adding child nodes, etc.). I want to be able to use this control to manage or navigate any hierarchical data structures I will create. I currently have it working for any data structure that implements the following interface (the interface need not actually be implemented, however, only the presence of these members is required):
interface ITreeItem
{
string Header { get; set; }
IEnumerable Children { get; }
}
Then in my UserControl, I use templates to bind my tree to the data structure, like so:
<TextBlock x:Name="HeaderTextBlock" Text="{Binding Path=Header}" />
What I would like to do is define the name of each of these members in my RichTreeView, allowing it to adapt to a range of different data structures, like so:
class MyItem
{
string Name { get; set; }
ObservableCollection<MyItem> Items;
}
<uc:RichTreeView ItemSource={Binding Source={StaticResource MyItemsProvider}}
HeaderProperty="Name" ChildrenProperty="Items" />
Is there any way to expose the Path of a binding inside a UserControl as a public property of that UserControl? Is there some other way to go about solving this problem?
Perhaps this might help:
Create a new Binding when you set the HeaderProperty property on the Header dependency property:
Header property is your normal everyday DependencyProperty:
public string Header
{
get { return (string)GetValue(HeaderProperty); }
set { SetValue(HeaderProperty, value); }
}
public static readonly DependencyProperty HeaderProperty =
DependencyProperty.Register("Header", typeof(string), typeof(ownerclass));
and the property of your HeaderProperty works as follows:
public static readonly DependencyProperty HeaderPropertyProperty =
DependencyProperty.Register("HeaderProperty", typeof(string), typeof(ownerclass), new PropertyMetadata(OnHeaderPropertyChanged));
public string HeaderProperty
{
get { return (string)GetValue(HeaderPropertyProperty); }
set { SetValue(HeaderPropertyProperty, value); }
}
public static void OnHeaderPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
if (args.NewValue != null)
{
ownerclass c = (ownerclass) obj;
Binding b = new Binding();
b.Path = new PropertyPath(args.NewValue.ToString());
c.SetBinding(ownerclass.HeaderProperty, b);
}
}
HeaderProperty is your normal everyday DependencyProperty, with a method that is invoked as soon as the HeaderProperty changes. So when it changes , it creates a binding on the Header which will bind to the path you set in the HeaderProperty. :)

Categories

Resources