Hidden public property in WPF control - c#

I am writing a custom control in WPF that works in this way: user sets some property which type is some class. Then, the control examines this object and generates some collection, which is to be displayed in UI via data binding.
In order for data binding to work, this collection should be a public property, but for the sake of incapsulation I do not want it to be public.
What is the best practice in such a situation?

You can use the Browsable attribute to hide property from property grid and the EditorBrowsable attribute to hide it from the XAML\CS editor. Or you can override the OnApplyTemplate method and assign your property value to the target element. You can get target element using the GetTemplateChild method.

Related

Elegant way of exposing ItemContainerGenerator in custom control

What's the elegant way of exposing ItemContainerGenerator from custom control?
I have ItemsSource property on my custom control and I would like to access UIElement corresponding to the bound item outside of it.
I don't have access to the ItemsControl nor ItemsContainerGenerator outside of my control. Should I expose ItemsControl or ItemContainerGenerator as a property, or maybe add a method for retrieving the UIElement?
I need to show the popup near the selected item. Maybe the popup should be a part of the control then I wouldn't have to do this?
If you want to be able to access the entire child ItemsControl, create a public read-only property that returns it.
If you only want to expose the ItemContainerGenerator, create a read-only property that returns it, e.g.:
public ChildItemContainerGenerator => childControl.ItemContainerGenerator;
If it makes no sense to expose the entire ItemContainerGenerator, create a public method that uses the ItemContainerGenerator internally to perform whatever you want to.
Which option to choose all comes down to your requirements actually.

How to check if property bound from inside custom control

I have custom control which have OperationMode and depending on this property I need to do certain things.
I also have other dependency properties like Property1 and Property2. I need to make sure that when user uses control in one way (certain OperationMode) then control doesn't have any bindings to Property1
So, I wonder if there any way to programmaticaly check to make sure that property have or don't have bindings associated with specific dependency property?
You can use the control's GetBindingExpression to test if a binding has been applied to a dependency property:-
bool property1IsBound = GetBindingExpression(Property1Property) != null;

What's the framework mechanism behind dependency properties?

I have been reading about dependency properties in several books but all have one thing in common, they just tell us how they are implemented( using static readonly DependencyProperty etc.) but does not tell the exact way they work from inside.
I mean they are implemented as static but still applies to all objects.
Second point of confusion is attached properties.
Is there any tutorial available that can explain all these concepts in an easy way?
My mental model of how dependency properties work:
Any DependencyObject class implements two special properties. One, a static property of the class, is a dictionary of DependencyProperty objects. Every instance of the class can look inside that dictionary to find metainformation about each DependencyProperty - the property's name, its type, any callbacks that have to be called when it's get and set, how it participates in property inheritance, and so on. When you register a dependency property, you're adding an entry to this dictionary.
The other property is an instance property: it's a dictionary, keyed by DependencyProperty, that contains the local value of each DependencyProperty, if it has been set.
The SetValue and GetValue methods that you implement in the setter and getter of the CLR property are basically lazy evaluation on steroids. Instead of storing and retrieving the value of the property in a backing field, they store and retrieve the value of the property in the value dictionary.
The magic of dependency properties is in what GetValue and SetValue actually do.
GetValue looks up the value for the property in the object's value dictionary. If it doesn't find it, it calls GetValue on the parent element, to get what the parent element thinks the value is. For instance, when you create a TextBox in a Window, anything that looks at the TextBox's FontFamily is actually calling GetValue. Unless you've explicitly set the font, there's no entry in its dictionary for that property. So GetValue asks the parent element for the value. The parent element may or may not have FontFamily set; if not, its call to GetValue to returns the value from its parent. And so on, until the Window object is reached and the actual FontFamily value is found.
If you set FontFamily on the TextBox, SetValue stores the value in the value dictionary. The next time anything needs to get the value of the FontFamily for that TextBox, GetValue finds the value in the dictionary and returns it, so it doesn't need to ask the parent element.
If you set FontFamily on the Window, SetValue not only updates the value in Window's value dictionary, it fires off a property-change event that everything dependent on the property hears. (That's why they're called dependency properties, remember.) And if the thing depending on the property is itself a dependency property, it fires off its own property-change events. This is how it is that changing the FontFamily on the Window changes the font for every control in the window and also prompts WPF to re-render the controls that have changed.
Attached properties work using the same kind of approach. Any object that can have attached properties has a dictionary that the attached properties' values are stored in. When you set Grid.Column on a CheckBox in XAML, you're just adding an entry to that CheckBox's dictionary. When the Grid needs to know what column the CheckBox is in, it looks the value up from that dictionary. When you set Grid.IsSharedSizeScope to True on an object, that object's dictionary will contain a new property - a dictionary that contains widths/heights for each SharedSizeKey.
I should emphasize that this is my mental model. I haven't sat down with Reflector and looked at the actual implementation of Register, GetValue, and SetValue to figure out how they actually work. I may be wrong about the details. But it's a model that accurately predicts how this stuff behaves, so it's good enough.
The concept of storing property values in dictionaries is pretty weird to C# programmers. It's old hat to Python programmers, though. In Python, all class properties - all objects, in fact - are stored in dictionaries, and so you can get to their value either through property accessors or just by looking them up. Dependency properties and attached properties are just another way in which .NET, having stolen everything Java had that was worth stealing, is now plundering Python. (Or from wherever Python plundered them from.) Learning Python has made me a much better C# programmer; I recommend it to any C# developer who hasn't done it yet.
Here is a tutorial on dependency properties http://www.wpftutorial.net/DependencyProperties.html that explains a little bit about how they work.
The short explanation of why the DependencyProperty object is in a static field is that it represents the description of the property, not the value of the property. Each DependencyObject has a mapping from DependencyProperty objects to their values.
This is also how attached properties work. Because each DependencyObject is storing a mapping from any DependencyProperty to a value, any type can create a new DependencyProperty and set it on any existing DependencyObject.
just see this post by joshsmith it has some additional informatin in it
http://joshsmithonwpf.wordpress.com/2007/06/22/overview-of-dependency-properties-in-wpf/
You can see below a very basic example of dependency property that creates a custom control text box in which space will be not allowed means user can not type space into text box.
1) Create a class with the name of ValidatedTextBox and write the following code in this class file:
public class ValidatedTextBox : TextBox
{
public ValidatedTextBox()
{
}
public static readonly DependencyProperty IsSpaceAllowedProperty =
DependencyProperty.Register("IsSpaceAllowed", typeof(bool), typeof(ValidatedTextBox));
public bool IsSpaceAllowed
{
get { return (bool)base.GetValue(IsSpaceAllowedProperty); }
set { base.SetValue(IsSpaceAllowedProperty, value); }
}
protected override void OnPreviewKeyDown(KeyEventArgs e)
{
base.OnPreviewKeyDown(e);
if (!IsSpaceAllowed && (e.Key == Key.Space))
{
e.Handled = true;
}
}
}
2) Now use the above control into your .XAML file
a) Add namespace of custom control text box like below:
xmlns:CustomControls="clr-namespace: ValidatedTextBox;assembly= ValidatedTextBox "
b) Now, use custom control text box like below:
<CustomControls:ValidatedTextBox IsSpaceAllowed="False" x:Name="MyTextBox" />
It will create a custom control text box that will not allow space. So, Basically Dependency property allows to add feature, extend feature of any control.

WPF - Dynamic tooltip

I have a class ToolTipProvider
which has a method
string GetToolTip(UIElement element)
which will return a specific tooltip for the UIElement specified, based on various factors including properties of the UIElement itself and also looking up into documentation which can be changed dynamically. It will also probably run in a thread so when the form first fires up the tooltips will be something like the visual studio 'Document cache is still being constructed', then populated in the background.
I want to allow this to be used in any wpf form with the minimum effort for the developer. Essentially I want to insert an ObjectDataProvider resource into the Window.Resources to wrap my ToolTipProvider object, then I think I need to create a tooltip (called e.g. MyToolTipProvider) in the resources which references that ObjectDataProvider, then on any element which requires this tooltip functionality it would just be a case of ToolTip="{StaticResource MyToolTipProvider}"
however I can't work out a) how to bind the actual elemnt itself to the MethodParameters of the objectdataprovider, or b) how to force it to call the method each time the tooltip is opened.
Any ideas/pointers on the general pattern I need? Not looking for complete solution, just any ideas from those more experienced
Create a new user control which functions as a tool-tip view factory.
Use your control as the tool-tip, passing any data you need for the factory to your control using binding (e.g. the data, the containing control, ...)
<AnyControl>
<AnyControl.ToolTip>
<YourToolTipControl Content="{Binding}" />
</AnyControl.ToolTip>
</AnyControl>
Not calling myself an expert, but I'd probably attempt such a feature with an attached property. This would be attachable to any element in your UI and you can specify an event handler that gets access to the object to which the property is being attached as well as the value passed to the attached property. You can keep a reference to the element to which your attached property was attached and you would then be able to change the ToolTip whenever you want.

How do I hide some of the default control properties at design-time (C#)?

I have a custom control that I made. It inherits from System.Windows.Forms.Control, and has several new properties that I have added. Is it possible to show my properties (TextOn and TextOff for example) instead of the default "Text" property.
My control works fine, I'd just like to de-clutter the property window.
You could either override them (if they can be overriden) and apply the Browsable attribute, specifying false, or create a new version of the property and apply the same attribute (this second approach doesn't always appear to work so YMMV).
Also, you can use a custom TypeConverter for your type and override the GetProperties method to control what properties get displayed for your type. This approach is more robust to the underlying base classes changing but can take more effort, depending on what you want to achieve.
I often use a combination of the Browsable attribute and a custom TypeConverter.
Override the property and add [Browsable(false)].
You might also want to add [EditorBrowsable(EditorBrowsableState.Never)], which will hide the property in IntelliSense in the code editor. Note that it will only be hidden in a separate solution from the original control.
using System.ComponentModel;
[Browsable(false), DesignerSerializationVisibility(
DesignerSerializationVisibility.Hidden)]
public int MyHiddenProp {get; set; }
worked for me in that way, that it would not appear in designer-properties, AND the propertiy will not be initialized by the designer, which would override my own initialisation....
You are looking for design-time attributes, specifically the BrowsableAttribute.
DefaultPropertyAttribute sets which property is the default one to edit.

Categories