我有一个小问题(我希望)。我有一个wpf项目,我使用MVVM,但我需要设置文本框的"SelectedText"属性。"selectedText"不是一个依赖属性,所以我不能使用绑定…我该如何解决这个问题?
如果您只需要从VM到控件的值分配,您可以使用这样的AttachedProperty
。
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);
}
}
和
的用法<!-- Pls note, that in the Binding the property 'SelectedText' on the VM is refered -->
<TextBox someNs:AttachedProperties.SelectedText="{Binding SelectedText}" />