I have a small (I hope) problem. I have a wpf project and I use MVVM, but I need to set the "SelectedText" property of the textbox. The "selectedText" is not a dependency property so, I can't use bindings... How can I solve this problem?
Dependency properties are used when you want data binding in a UserControl , and is the standard method of data binding for the WPF Framework controls. DPs have slightly better binding performance, and everything is provided to you when inside a UserControl to implement them.
Existing read-only dependency properties For example, the Windows Presentation Foundation (WPF) framework implements the IsMouseOver property as read-only because its value should only be determined by mouse input. If IsMouseOver allowed other inputs, its value might become inconsistent with mouse input.
Windows Presentation Foundation (WPF) provides a set of services that can be used to extend the functionality of a type's property. Collectively, these services are referred to as the WPF property system. A property that's backed by the WPF property system is known as a dependency property.
In WPF applications, dependency property is a specific type of property which extends the CLR property. It takes the advantage of specific functionalities available in the WPF property system. A class which defines a dependency property must be inherited from the DependencyObject class.
If you only need the value assignment from the VM to the control you could use an AttachedProperty
like this.
public class AttachedProperties
{
private static DependencyProperty SelectedTextProperty =
DependencyProperty.RegisterAttached("SelectedText", typeof(string),
typeof(AttachedProperties), new PropertyMetadata(default(string), OnSelectedTextChanged)));
private static void OnSelectedTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var txtBox = d as TextBox;
if (txtBox == null)
return;
txtBox.SelectedText = e.NewValue.ToString();
}
public static string GetSelectedText(DependencyObject dp)
{
if (dp == null) throw new ArgumentNullException("dp");
return (string)dp.GetValue(SelectedTextProperty);
}
public static void SetSelectedText(DependencyObject dp, object value)
{
if (dp == null) throw new ArgumentNullException("dp");
dp.SetValue(SelectedTextProperty, value);
}
}
And the usage
<!-- Pls note, that in the Binding the property 'SelectedText' on the VM is refered -->
<TextBox someNs:AttachedProperties.SelectedText="{Binding SelectedText}" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With