Would it be possible for an Adorner to be hidden / displayed depending on the value of a property in a class ?
Should I use attached properties for this purpose ?
If so, how exactly can the Adorner's visibility be controlled; do I have to manually remove it / add it to the Adorner Layer within the Dependency Object's OnChanged event ?
This is just a very quick code representation of what I'm trying to do:
(Note: I'm not even sure if its the right way of doing things. I want the Adorner's visibility to be controlled by the value of a property that is modified by the code in my business model. The problem with Attached Properties is that its the control's responsibility to update the value of the property instead of the code in my business domain.)
public static class IsValidBehavior
{
public static readonly DependencyProperty IsValidProperty = DependencyProperty.RegisterAttached("IsValid",
typeof(bool),
typeof(IsValidBehavior),
new UIPropertyMetadata(false, OnIsValidChanged));
public static bool GetIsValid(DependencyObject obj)
{
return (bool)obj.GetValue(IsValidProperty);
}
public static void SetIsValid(DependencyObject obj, bool value)
{
obj.SetValue(IsValidProperty, value);
}
private static void OnIsValidChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
UIElement element = dependencyObject as UIElement;
if (element == null)
return;
if ((bool)e.NewValue == true)
{
// Display the Adorner
}
else
{
// Hide the Adorner
}
}
}
Well, if I right understood your question, in WPF you have 2 ways to do that, from code or from XAML. From code, you more or less already did, in XAML you can do something like this, I think:
Visibility="{Binding Path=MyVisibilityVariant,
Converter={StaticResource VisibilityConverter}}
In other words bind it to some property. My general suggestion: is use XAML whenever you can, considering a couple of variants:
XAML declaration makes the software very scallable, but also more complex (consider your, or your group cappabilities, somehow doing the stuff in code behind is best, if not only solution available)
Consider you deadlines, cause on XAML stuff implementing/debugging/fixing you will spend more time then on code.
EDIT
Defining custom Adorder in order to be able to define it in XAML
Related
WPF - Bindable chat view with selectable text
I want to create a simple text chat app using WPF. And of course user should be able to select and, for example, copy text.
It's very easy to use, for example, ListView with ItemsSource bound to messages. And appearance can be tuned, but the main problem is text selection. It's possible to select text only in one single control (one message).
At the moment i use WebBrowser for showing messages. So i have tons of HTML+JS+CSS. I think i dont even have to say how terrible it is.
Can you please point me to right direction?
You could take a look at the FlowDocument for that. This class can be used for customizing the appearance of the blocks (paragraphs) similar to an ItemsControl, it can contain UI controls too (in case you need it). And of course, the text selection will work across the whole document.
Unfortunately, the FlowDocument doesn't support bindings, so you will have to write some code for that.
Let me give you an example. You could use a Behavior from the System.Windows.Interactivity namespace to create a reusable functionality extension for the FlowDocument class.
This is what you could start with:
<FlowDocumentScrollViewer>
<FlowDocument ColumnWidth="400">
<i:Interaction.Behaviors>
<myApp:ChatFlowDocumentBehavior Messages="{Binding Messages}">
<myApp:ChatFlowDocumentBehavior.ItemTemplate>
<DataTemplate>
<myApp:Fragment>
<Paragraph Background="Aqua" BorderBrush="BlueViolet" BorderThickness="1"/>
</myApp:Fragment>
</DataTemplate>
</myApp:ChatFlowDocumentBehavior.ItemTemplate>
</myApp:ChatFlowDocumentBehavior>
</i:Interaction.Behaviors>
</FlowDocument>
</FlowDocumentScrollViewer>
(the i namespace is xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity")
So there is our ChatFlowDocumentBehavior which has a bindable Messages property for displaying the chat messages. Also, there is an ItemTemplate property where you define how a single chat message should look like.
Note the Fragment class. This is just a simple wrapper (code below). The DataTemplate class won't accept a Paragraph as its content, but we need our items to be Paragraphs.
You can configure that Paragraph as you wish (like colors, fonts, maybe additional child items or controls etc.)
So, the Fragment class is a simple wrapper:
[ContentProperty("Content")]
sealed class Fragment : FrameworkElement
{
public static readonly DependencyProperty ContentProperty = DependencyProperty.Register(
nameof(Content),
typeof(FrameworkContentElement),
typeof(Fragment));
public FrameworkContentElement Content
{
get => (FrameworkContentElement)GetValue(ContentProperty);
set => SetValue(ContentProperty, value);
}
}
The behavior class has a little bit more code but isn't complicated.
sealed class ChatFlowDocumentBehavior : Behavior<FlowDocument>
{
// This is our dependency property for the messages
public static readonly DependencyProperty MessagesProperty =
DependencyProperty.Register(
nameof(Messages),
typeof(ObservableCollection<string>),
typeof(ChatFlowDocumentBehavior),
new PropertyMetadata(defaultValue: null, MessagesChanged));
public ObservableCollection<string> Messages
{
get => (ObservableCollection<string>)GetValue(MessagesProperty);
set => SetValue(MessagesProperty, value);
}
// This defines how our items will look like
public DataTemplate ItemTemplate { get; set; }
// This method will be called by the framework when the behavior attaches to flow document
protected override void OnAttached()
{
RefreshMessages();
}
private static void MessagesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (!(d is ChatFlowDocumentBehavior b))
{
return;
}
if (e.OldValue is ObservableCollection<string> oldValue)
{
oldValue.CollectionChanged -= b.MessagesCollectionChanged;
}
if (e.NewValue is ObservableCollection<string> newValue)
{
newValue.CollectionChanged += b.MessagesCollectionChanged;
}
// When the binding engine updates the dependency property value,
// update the flow doocument
b.RefreshMessages();
}
private void MessagesCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
AddNewItems(e.NewItems.OfType<string>());
break;
case NotifyCollectionChangedAction.Reset:
AssociatedObject.Blocks.Clear();
break;
}
}
private void RefreshMessages()
{
if (AssociatedObject == null)
{
return;
}
AssociatedObject.Blocks.Clear();
if (Messages == null)
{
return;
}
AddNewItems(Messages);
}
private void AddNewItems(IEnumerable<string> items)
{
foreach (var message in items)
{
// If the template was provided, create an instance from the template;
// otherwise, create a default non-styled paragraph instance
var newItem = (Paragraph)(ItemTemplate?.LoadContent() as Fragment)?.Content ?? new Paragraph();
// This inserts the message text directly into the paragraph as an inline item.
// You might want to change this logic.
newItem.Inlines.Add(message);
AssociatedObject.Blocks.Add(newItem);
}
}
}
Having this as a starting point, you can extend the behavior to suit your needs. E.g. add event handling logic for removing or reordering of the messages, implement comprehensive message templates etc.
It's almost always possible to implement the functionality with as less code as possible, using XAML features: styles, templates, resources etc. However, for the missing features, you just need to fall back to the code. But in that case, always try to avoid code-behind in the views. Create Behaviors or attached properties for that.
A textbox should give you what you are looking for I think. You will need to do the styling so it looks like you want but here is code:
XAML:
<TextBox Text="{Binding AllMessages}"/>
ViewModel:
public IEnumerable<string> Messages { get; set; }
public string AllMessages => GetAllMessages();
private string GetAllMessages()
{
var builder = new StringBuilder();
foreach (var message in Messages)
{
//Add in whatever for context
builder.AppendLine(message);
}
return builder.ToString();
}
You will probably want to use a RichTextBox for better formatting.
I have a Template Control which has a StackPanel as it's root. What I want is a way to make something like this:
<Controls:MyControl Kind="SomeKind"/>
And based on SomeKind the StackPanel's background would change. There would be a limited number of "Kinds", the same way there is a limited number of HorizontalAlignments in a Button, for example.
<Button HorizontalAlignment="Center"/>
I've searched in the internet a bit and it does seems like it involves Attached Properties, but I haven't found a clean, simple and easy-to-follow example for UWP. I've found some examples for WPF but they doesn't seem to work.
No you don't need attached properties since it's likely to be only associated within your custom control. What you need is a dependency property of an enum type.
Say if you have this enum -
public enum PanelBackgroundType
{
Orange,
Pink,
Offwhite
}
Then your dependency property will look something like this -
public PanelBackgroundType PanelBackgroundType
{
get { return (PanelBackgroundType)GetValue(PanelBackgroundTypeProperty); }
set { SetValue(PanelBackgroundTypeProperty, value); }
}
// Using a DependencyProperty as the backing store for PanelBackgroundType. This enables animation, styling, binding, etc...
public static readonly DependencyProperty PanelBackgroundTypeProperty =
DependencyProperty.Register("PanelBackgroundType", typeof(PanelBackgroundType), typeof(MyControl),
new PropertyMetadata(PanelBackgroundType.Offwhite, (s, e) =>
{
if ((PanelBackgroundType)e.NewValue != (PanelBackgroundType)e.OldValue)
{
// value really changed, invoke your changed logic here
var control = (MyControl)s;
switch ((PanelBackgroundType)(e.NewValue))
{
case PanelBackgroundType.Orange:
control.MyStackPanel.Background = new SolidColorBrush(Colors.Orange);
break;
case PanelBackgroundType.Pink:
control.MyStackPanel.Background = new SolidColorBrush(Colors.Pink);
break;
case PanelBackgroundType.Offwhite:
default:
control.MyStackPanel.Background = new SolidColorBrush(Colors.Wheat);
break;
}
}
else
{
// else this was invoked because of boxing, do nothing
}
}));
Note that I have a check (PanelBackgroundType)e.NewValue != (PanelBackgroundType)e.OldValue inside the property changed callback to see if the value of the dp really has changed. This may seem redundant but according to MSDN, this is the best practise as -
If the type of a DependencyProperty is an enumeration or a structure,
the callback may be invoked even if the internal values of the
structure or the enumeration value did not change. This is different
from a system primitive such as a string where it only is invoked if
the value changed. This is a side effect of box and unbox operations
on these values that is done internally. If you have a
PropertyChangedCallback method for a property where your value is an
enumeration or structure, you need to compare the OldValue and
NewValue by casting the values yourself and using the overloaded
comparison operators that are available to the now-cast values. Or, if
no such operator is available (which might be the case for a custom
structure), you may need to compare the individual values. You would
typically choose to do nothing if the result is that the values have
not changed.
Have a look at this link: https://msdn.microsoft.com/en-us/windows/uwp/xaml-platform/custom-dependency-properties
It will show you how to add custom dependency properties for an object that you'll be able to edit in the UI.
I'll give you a quick example of what you want event though I recommend you to take a look at Microsoft's docs
public sealed partial class MyControl : UserControl
{
public MyControl()
{
this.InitializeComponent();
}
public static readonly DependencyProperty KindProperty = DependencyProperty.Register(
"Kind", typeof(string), typeof(MyControl),
new PropertyMetadata(null, new PropertyChangedCallback(OnKindChanged)));
public string Kind
{
get { return (string)GetValue(KindProperty); }
set { SetValue(KindProperty, value); }
}
private static void OnKindChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// Executed method when the KindProperty is changed
}
}
I'm new to wpf, as the title suggests. I was using wpf as it was winforms (what's all that binding non sense anyway) until, of course, I tried it and got blown away.
So I was digging into user controls and dependency properties. I read that, in order to get the ui to remain in sync with what's under the hood you need to use observable collections, notifypropertychanged / changing and dependency properties for the stuff that you use.
My question is this:
Let's say I have this dep. prop. for a user control (type of Media.Color) :
public Color Color
{
get { return (Color)GetValue(ColorProperty); }
set { SetValue(ColorProperty, value); }
}
The xaml uses it for a binding, it works, all is good. But, when it gets updated, I would like to do something with it in code.
So I tried putting a Console.writeline("fired") like so:
public Color Color
{
get { return (Color)GetValue(ColorProperty); }
set {
Console.WriteLine("Fired");
SetValue(ColorProperty, value);
}
}
No dice. Could someone please enlighten me how this stuff works? I am obviously missing something (just the other day someone on stack told me about MouseCapture so... ).
Thank you for your time.
Edit
http://www.wpftutorial.net/DependencyProperties.html
Basically it says, in big bold letters,
Important: Do not add any logic to these properties, because they are
only called when you set the property from code. If you set the
property from XAML the SetValue() method is called directly.
If you are using Visual Studio, you can type propdp and hit 2x tab to
create a dependency property.
And goes on to explain why and how you should proceed.
Solution
So, I tried what #Krishna suggested, and my user control crashed and burned.
Here was my dep prop. (as it was before asking this question).
public static readonly DependencyProperty ColorProperty = DependencyProperty.Register("Color", typeof(Color), typeof(ColorPickerMaster), new PropertyMetadata(default(Color)));
Turns out the problem was using
(...) new Prop.Metadata(null, OnPropChanged)
Using
public static readonly DependencyProperty ColorProperty = DependencyProperty.Register("Color", typeof(Color), typeof(ColorPickerMaster), new PropertyMetadata(OnColorChanged));
private static void OnColorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Console.WriteLine(e.NewValue);
}
yields a beautiful win.
Thank you for your time and answers.
When it comes to DependencyProperties you use property changed callback to track changes to your property like below example. And then you use e.NewValue and e.OldValue to write your logic. More about DependencyProperties on MSDN
public Color color
{
get { return (Color)GetValue(colorProperty); }
set { SetValue(colorProperty, value); }
}
public static readonly DependencyProperty colorProperty =
DependencyProperty.Register("color", typeof(Color), typeof(YourClass), new PropertyMetadata(null,colorChanged));
private static void colorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
YourClass c = d as YourClass;
if(c!=null)
{
}
}
From MSDN - XAML Loading and Dependency Properties:
The current WPF implementation of its XAML processor is inherently dependency property aware. The WPF XAML processor uses property system methods for dependency properties when loading binary XAML and processing attributes that are dependency properties. This effectively bypasses the property wrappers. When you implement custom dependency properties, you must account for this behavior and should avoid placing any other code in your property wrapper other than the property system methods GetValue and SetValue.
If you want to add custom logic in a setter you will have to make it a simple field (not a DependecyProperty) implement INotifyPropertyChanged and bind to it.
I have a need to set Content property of a ContentPresenter to a DynamicResource, which key is known at runtime. DynamicResource's Key is not a dependency property, so I cannot insert a binding there, and that's why I've created an attached property, which serves as a proxy for the Content:
public static class ContentPresenterHelper {
private static void ContentResourceKeyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
var element = d as ContentPresenter;
if (element != null) {
element.SetResourceReference(ContentPresenter.ContentProperty, e.NewValue);
}
}
public static readonly DependencyProperty ContentResourceKeyProperty = DependencyProperty.RegisterAttached("ContentResourceKey",
typeof(object),
typeof(ContentPresenterHelper),
new PropertyMetadata(String.Empty, ContentResourceKeyChanged));
public static void SetContentResourceKey(ContentPresenter element, object value) {
element.SetValue(ContentResourceKeyProperty, value);
}
public static object GetContentResourceKey(ContentPresenter element) {
return element.GetValue(ContentResourceKeyProperty);
}
}
I'm using it in the following way:
<ContentPresenter u:ContentPresenterHelper.ContentResourceKey="{Binding SomeProp}" />
I've used similar approach when assigning dynamically image from resources to an Image's Source property and that worked.
However, in this particular case attempt to solve the problem in the way I've shown results in an infinite recursion:
PresentationFramework.dll!System.Windows.FrameworkElement.IsLoaded.get() Unknown
PresentationFramework.dll!MS.Internal.FrameworkObject.IsLoaded.get() Unknown
PresentationFramework.dll!System.Windows.BroadcastEventHelper.IsParentLoaded(System.Windows.DependencyObject d) Unknown
PresentationFramework.dll!System.Windows.FrameworkElement.IsLoaded.get() Unknown
PresentationFramework.dll!MS.Internal.FrameworkObject.IsLoaded.get() Unknown
PresentationFramework.dll!System.Windows.BroadcastEventHelper.IsParentLoaded(System.Windows.DependencyObject d) Unknown
PresentationFramework.dll!System.Windows.FrameworkElement.IsLoaded.get() Unknown
PresentationFramework.dll!MS.Internal.FrameworkObject.IsLoaded.get() Unknown
...
Why is it so? How can I solve this problem?
When messing around with ContentPresenter, always remember that ContentPresenter.Content is a very special property: it affects the DataContext. In combination with data binding this can produce all sorts of weird effects. Generally speaking, binding ContentPresenter.Content through DataContext is not reliable and should be avoided. Try using ContentControl, as it does not connect its DataContext to Content in this manner. Also, instead of an attached property, I'd write a converter to look up your dynamic resource by key, and use it to bind Content directly, but it's a matter of taste.
I was looking at this question, but I don't understand how to actually USE the created AttachedProperty. The problem is trying to have a binding on the source of the WebBrowser control.
The code there looks like:
public static class WebBrowserUtility
{
public static readonly DependencyProperty BindableSourceProperty =
DependencyProperty.RegisterAttached("BindableSource", typeof(string), typeof(WebBrowserUtility), new UIPropertyMetadata(null, BindableSourcePropertyChanged));
public static string GetBindableSource(DependencyObject obj)
{
return (string) obj.GetValue(BindableSourceProperty);
}
public static void SetBindableSource(DependencyObject obj, string value)
{
obj.SetValue(BindableSourceProperty, value);
}
public static void BindableSourcePropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
WebBrowser browser = o as WebBrowser;
if (browser != null)
{
string uri = e.NewValue as string;
browser.Source = uri != null ? new Uri(uri) : null;
}
}
}
and
<WebBrowser ns:WebBrowserUtility.BindableSource="{Binding WebAddress}"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ScrollViewer.VerticalScrollBarVisibility="Disabled"
Width="300"
Height="200" />
The WebAddress, what is that exactly? This is my understanding (which is probably wrong):
There's an AttachedProperty that can be attached to any object, and in this particular case, it is basically just attaching a property called BindableSource which is of type String.
When we have the "{Binding WebAddress}" it means that in some c# code somewhere that handles this .xaml file there's something that looks like:
public String WebAddress
{
// get and set here? not sure
}
And to take advantage of the property changed, I can called RaisedPropertyChanged and it will fire that static method up there?
Even when I look at it, it doesn't seem right, but I can't find anything online to help me.
There's an AttachedProperty that can be attached to any object, and in this particular case, it is basically just attaching a property called BindableSource which is of type String.
You might want to read the MSDN article on attached properties.
It is rather simple: Dependency properties work with dictionaries in which controls are associated with their values for a property, this makes it quite easy to add something like attached properties which can extend a control.
In the RegisterAttached method of the attached property a PropertyChangedCallback is hooked up which will be executed if the value changes. Using a dependency property enables binding which is the point of doing this in the first place. All the property really does is call the relevant code to navigate the browser if the value changes.
When we have the "{Binding WebAddress}" it means that in some c# code somewhere that handles this .xaml file there's something that looks like [...]
The binding references some public property or depedency property (not a field) called WebAddress inside the DataContext of the WebBrowser. For general information on data-binding see the Data Binding Overview.
So if you want to create a property which should be a binding source you either implement INotifyPropertyChanged or you create a DependencyProperty (they fire change notifications on their own and you normally do only create those on controls and UI-related classes)
Your property could look like this:
public class MyModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
private string _webAddress;
public string WebAddress
{
get { return _webAddress; }
set
{
if (value != _webAddress)
{
_webAddress = value;
NotifyPropertyChanged("WebAddress");
}
}
}
}
Here you have to raise the PropertyChanged event in the setter as you suspected. How to actually declare working bindings in XAML is a rather broad topic sp i would like to direct you to the aforementioned Data Binding Overview again which should explain that.
And to take advantage of the property changed, I can called RaisedPropertyChanged and it will fire that static method up there?
The event is fired to trigger the binding to update, this in turn changes the value of the attached property which in turn causes the PropertyChangedCallback to be executed which eventually navigates the browser.