Reputation: 297
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?
Upvotes: 7
Views: 2238
Reputation: 4865
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}" />
Upvotes: 10